title: Bicycle Tail Light project

text:
# Question
Title: Bicycle Tail Light project
For my college course we currently have to carry out a project of our own choice. I chose to make a Tail light system, with strobing indicators, fog-light and brake-light.

The lighting uses Neopixel strips and rings, with the indicator sections consisting of 2 neopixel strip 6 (in parallel); the fog light using a neopixel jewel; and the brake light using a neopixel ring 16.

The indicators need to strobe outward from the centre of the device (in the desired direction, left/right) based on a button input. The fog-light should turn on when the device is activated by switch, and the brake-light will turn on when receiving an input from another button.

I've only ever coded using Python during GCSE and can't wrap my head around Arduino code. Currently using tinkercad for creating this as I don't have any arduino kit, and don't want to spend out the money on unneeded components.

Any help is appreciated, and if a link to the tinkercad circuit would be useful let me know.

# Answer
Break down your project into steps, both hardware and software, and tackle a step at a time.

First do a block diagram of the system, showing the different components, the layout of the control buttons, etc.

Then map out the desired behavior, perhaps using a flowchart. What should it do when you first turn it on? How will it respond to different button inputs? Will it continue to flash in the current pattern indefinitely until there's another input? Will there be a cancel button?

Then read up on how to power and control NeoPixel LEDs. I believe they use I2C? Are there any NeoPixel libraries you can use?

You might then try using a circuit simulator to create a virtual prototype of your circuit. Figure out how big a battery & voltage regulator you're going to need. (If you're running off of batteries you should use a switching or "buck" type voltage regulator rather than a linear voltage regulator since they are much more efficient. Just make sure you pick a regulator that can provide enough current for all your LEDs plus your Arduino, with a little extra left over.))

Once you get a virtual circuit working, it's time to use real hardware.

For a bike tail-light, you should think about how to make it weather-proof. are there waterproof enclosures you can use? What about waterproof NeoPixels? If there are no waterproof NeoPixels, what about waterproof enclosures with clear covers?

Buy the Arduino you're going to use, and at least a few of your NeoPixels. Work out how to control and flash a single LED. Then gradually add complexity to your project until you get it working.
> 1 votes

---
Tags: arduino-uno, rgb-led, led-strip
---


# Question
Title: Interrupt every second on ATTiny84 (and sleep the rest)
I'm building a digital watch just like in this post, except I'm using an ATTiny84. However, the ATTiny84 doesn't have an asynchronous Timer2 like the ATMega328 and does not have a power save mode, so it cannot wake up from the Timer2 interrupt as is suggested in that post.

I need to increment my 'seconds' counter every second, and I need to do it precisely so I don't lose/gain time (so I can't use the watchdog timer which, as I understand, does not use the crystal oscillator but rather its own imprecise clock). I was planning on just keeping the CPU on and using an external crystal, but it seems that that takes a lot of power (~3mA). Even with the SLEEP\_MODE\_IDLE, I could only get the current draw down to around (~1.2mA).

Like Nick Gammon suggested in that post, I feel like the real solution is to sleep when not changing the counter. Is there any way to wake up after a precise amount of time in the POWER\_DOWN or STAND\_BY modes?

# Answer
> 3 votes
> Is there any way to wake up after a precise amount of time in the POWER\_DOWN or STAND\_BY modes?

I'm afraid not. You will have to use a timer. Since the ATtiny84 does not have an asynchronous timer, you will have to keep your timer clocked. This means the clkIO clock domain has to stay active. Now, take a look at the table “*Active Clock Domains and Wake-up Sources in Different Sleep Modes*”, on page 33 of the ATtiny84 datasheet. It shown that “Idle” is the *only* sleep mode that keeps this clock domain active.

> Even with the SLEEP\_MODE\_IDLE, I could only get the current draw down to around (~1.2mA).

There are ways to bring this down. First, there is a collection of functions named `power_*_disable()` in the avr-libc. You can use these to power down every single peripheral except the one timer that you will be using.

Most importantly, you can save power by reducing the clock speed. Since these devices have extremely little leakage current, the current draw is roughly proportional to the clock frequency. You can then achieve huge power savings by drastically reducing that frequency. Obviously, your processing power will also suffer, but this may not be an issue for a simple binary clock.

I think the best option for you is to clock your ATtiny84 off a 32.768 kHz watch crystal. See the section 6.2.4 – *Low-Frequency Crystal Oscillator* in the datasheet. These crystals can be very accurate, as they are specifically designed for time keeping. And the frequency is so low that the current draw from the MCU will likely be negligible compared to whatever other components are in your clock.

**Edit**: answering the question in the comment.

> Wouldn't waking from idle still use the watchdog timer though? Or is there a way to wake up based on the 32.768 kHz crystal?

As the watchdog timer is way too inaccurate, it is of no use to you. Instead, you would use either Timer 0 or Timer 1, and configure it to deliver an interrupt every 32,768 CPU cycles. This interrupt will be your 1 Hz wakeup source.

You can do this with either timer, in either CTC or fast PWM mode. You have to configure the prescaler and the TOP value such that

prescaler\_factor × (TOP + 1) = 32,768

Then, enable the relevant interrupt, and define the corresponding ISR that will advance your clock by one second.

---
Tags: interrupt, timers, attiny
---


title: 2 SPI devices conflict

text:
# Question
Title: 2 SPI devices conflict
I want to connect a W5500 ethernet Module and an SD card module to arduino Uno using SPI (with different CS pins of course). When connected separately they work fine but when connected in the same circuit the ethernet module doesn't get a correct ip address and always gets an address 255.255.255.255. To me the ethernet module is the likely culprit as the SD card module works without problem even when the ethernet module is also connected.

Tried using Ethernet & Ethernet2 libraries but no difference. Tried manually assigning the IP address but it won't work. I have even set the CS pins HIGH in the setup before calling SD.begin & Ethernet.begin() to avoid both components "listening" at the same time but it still doesn't work. How can I fix it?

Here is the sketch I am working with. Although it doesn't use SD module but as mentioned above if SD module is connected in the circuit, ethernet module doesn't get incorrect ip address

```
#include <SPI.h>
#include <Ethernet2.h>

//IPAddress ip(192, 168, 1, 22);

// MAC address just has to be unique. This should work
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

EthernetServer server(80);

void setup()
{

  pinMode(8, OUTPUT); // SD module CS
  digitalWrite(8, HIGH);
  pinMode(10, OUTPUT); // Ethernet module CS
  digitalWrite(10, HIGH);
  delay(1);

  Serial.begin(9600);
  Ethernet.begin(mac);
  server.begin();
  Serial.print("Server started on: ");
  Serial.println(Ethernet.localIP());
}

void loop()
{
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client)
  {
    while (client.connected())
    {
      // send a standard http response header
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println();

      // send the body
      client.println("<html><body>");
      client.println("<h1>Arduino Server</h1>");
      client.print("<p>A0=");
      client.print(analogRead(0));
      client.println("</p>");
      client.print("<p>millis=");
      client.print(millis());
      client.println("</p>");
      client.println("</body></html>");
      client.stop();
    }
    delay(1);
  }
}

```

Another sketch with reference to both SD and Ethernet Libraries

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

byte mac[] = { 0x00, 0xC3, 0xA2, 0xE6, 0x3D, 0x57 };
byte LED = 2;
char wServer[] = "media.wizards.com";
char wFile[] = "/images/magic/tcg/resources/rules/MagicCompRules_20140601.pdf";

EthernetClient myClient;

void setup() {
  //D53 on an Arduino Mega must be an output.
  pinMode(53, OUTPUT);

  pinMode(LED, OUTPUT);

  Serial.begin(9600);
  while (!Serial);

  Serial.print("Establishing network connection... ");

  if (Ethernet.begin(mac) == 0) {
    Serial.println("FAILED!");
    while (true) {
      digitalWrite(LED, HIGH);
      delay(500);
      digitalWrite(LED, LOW);
      delay(500);
    }
  }
  else {
    Serial.println("OK!");
  }
}

void loop() {

  Serial.print("Connecting to ");
  Serial.print(wServer);
  Serial.print("... ");

  if (myClient.connect(wServer, 80) == 1) {
    Serial.println("OK!");

    myClient.print("GET ");
    myClient.print(wFile);
    myClient.println(" HTTP/1.0");
    myClient.print("Host: ");
    myClient.println(wServer);
    myClient.println();

    if (SD.begin(8)) {
      if (SD.exists("MAGIC.PDF"))
        SD.remove("MAGIC.PDF");

      Serial.print("Saving response... ");
      digitalWrite(LED, HIGH);

      File dd = SD.open("MAGIC.PDF", FILE_WRITE);

      char lc;
      while (myClient.connected()) {
        if (myClient.available()) {
          char nc = myClient.read();
          if ((lc == 10) && (nc == 13)) {
            while (myClient.available() == 0);
            myClient.read();
            break;
          }
          else
            lc = nc;
        }
      }

      while (myClient.connected()) {
        if (myClient.available() > 0) {
          dd.write(myClient.read());
        }
      }

      dd.close();
      delay(500);
      Serial.println("OK");
      digitalWrite(LED, LOW);
    }
    else
      Serial.println("No SD card detected!");

    myClient.stop();
  }
  else
    Serial.println("FAILED!");

  delay(3600000);
  asm volatile(" jmp 0");

```

# Answer
I had the same problem with my SD card module.

I don't have too much knowledge about all details, but it is related that most SD card modules (the simple ones) do not have tri-state functionality, meaning they cannot cope with multiple SPI devices on the same bus.

Sadly, the Arduino has only one SPI connection, but there are solutions:
> 3 votes

---
Tags: arduino-uno, sd-card, ethernet
---


# Question
Title: Arduino as USB HID is slowed down when PC doesn't read events
I have an Arduino Micro that is acting as a HID device for a Linux PC.

I use this call to send the HID values:

`HID().SendReport(1, _values, sizeof(_values));`

This works in principle, but I noticed this issue:

If my Linux PC is not actively reading the events from the Arduino, then the Arduino is slowed down. My rotary encoders are missing signals, is one symptom.

But as soon as I read the events with my Linux PC, the Arduino loop() runs at full speed again.

I suspect that this is due to recv/send time out delays in the USB core code? Because I noticed this in USBCore.cpp:

`u8 timeout = 250; // 250ms timeout on send? TODO`

Anyway, I tried to solve this issue in the following manners:

Check for configuration and suspension with:

```
     if (USBDevice.configured())
      if (!USBDevice.isSuspended())
         ...

```

Which did not work.

I also tried monitoring the increments of the frame number:

```
  // See if USB shows activity.
  static uint8_t prev_fr_num = UDFNUML;
  static uint8_t num_times_idle = 0;
  uint8_t fr_num = UDFNUML;
  if (fr_num == prev_fr_num )
  {
    if (num_times_idle < 255)
      num_times_idle++;
  }
  else
  {
    num_times_idle = 0;
    prev_fr_num = fr_num;
  }

```

And then only send if num\_times\_idle is smaller than a threshold. Again, this did not help.

The only way to make it fast, is by reading the events with linux, like so:

`$ jstest /dev/input/js0`

or alternatively:

`$ evtest /dev/input/event5`

How can I have the USB HID stuff not slow down my loop code when the PC is not paying attention?

Thanks!

Bram

# Answer
> 2 votes
For those that hit the same issue, here is how I solved it:

Expose the `USB_SendSpace()` information in the HID interface by editing

**/usr/local/arduino-1.8.12/hardware/arduino/avr/libraries/HID/src/HID.cpp**

```
u8 HID_::SendSpace(void)
{
        return USB_SendSpace(pluggedEndpoint);
}

```

And adding the interface to `class HID_` in:

**/usr/local/arduino-1.8.12/hardware/arduino/avr/libraries/HID/src/HID.h**

That way, before calling `HID().SendReport()` you can check for send buffer space available by calling the `HID().SendSpace()` method.

If there is no space, just skip the SendReport() calls, and the Arduino loop() will no longer be slowed down by time outs.

---
Tags: usb, arduino-micro, linux, events, hid
---


# Question
Title: Can I use Visual Studio instead of Arduino IDE?
I think that Visual Studio is a great product! I find the Arduino IDE is limited in its features. For example the Arduino IDE does not have:

* Code prediction
* Error highlighting
* Previews of #define values
* Peek at code definition
* Jump to code definition
* and many more...

Since the Arduino ino & pde file types are basically C++, Can I use the Visual Studio IDE instead of Arduino IDE?

To be considered as a replacement, Visual Studio must be able to:

* Save & open ino & pde files.
* Compile my code.
* Download my code.
* Use existing/custom libraries from the Arduino IDE.
* Detect and display an Arduino project.

I would consider these features as a bonus:

* Arduino board selection.
* Debugging
    + Variable watch window
    + Breakpoints
    + Step through code
* Simulation
* Open the Arduino Examples
* Automatic board detection
* Serial Monitor

# Answer
I only use Visual Studio for Arduino programming. Arduino Plugin for Visual Studio
> 8 votes

# Answer
Atmel Studio 7 which is built with Visual Studio. Google "Atmel Studio 7" or click here. It has everything you want and it's released by the company that makes the atmega328 your Arduino is built on.
> 2 votes

# Answer
Note, this answer is not technically for the full edition of Visual Studio, rather Visual Studio Code.

Microsoft has released an Arduino extension for VS Code that can do most (all?) of the required items in the OP's list.

Added this answer as a free alternative to the accepted answer.
> 2 votes

# Answer
It's not exactly what you are asking, but maybe you would be willing to consider a solution based on Eclipse?

Eclipse has the advantage of being cross platform, so you can have the same experience no matter what your OS might be.

Although, for the sake of completeness, almost all you mentioned can be done even with vim, if adequately configured. But I wouldn't recommend it as first choice, if you have never used it before.
> -1 votes

---
Tags: arduino-ide, ide, visualstudio
---


title: What are the other IDEs for Arduino?

text:
# Question
Title: What are the other IDEs for Arduino?
The basic Arduino IDE lacks a lot of the sophistication present in other IDEs such as code completion, code collapsing, folder organisation, etc. Are there other IDEs that allow programming in C or C++ and improve on these aspects?

# Answer
There is an Arduino Eclipse plugin named sloeber! And Eclipse is an awesome cross-platform open-source IDE!

Stino is good. It requires Sublime Text 2 which has an indefinite free trial.

Visual Micro provides a full build system with debugger for Arduino in Microsoft Visual Studio. For advanced users it also allows the underlying Arduino source code to be viewed or modified, enabled projects and/or libraries to be edited from any location and shared in multiple projects alongside true cross-platform intellisense.

For more go to The Official Arduino Site

For development on Windows, there is a special edition from Arduino official IDE called arduino-erw, This edition much better the last one because it fixed a lot of lagging and stability issues!
> 65 votes

# Answer
Expanding on Fake Name's answer, there is also Visual Micro's Arduino plugin for Atmel Studio (built off Visual Studio). It shares the tools, sources and libraries with the Arduino IDE but provides all the code completion and other features of Visual Studio.

The Visual Micro plugin also works in all versions of Visual Studio. Provides Arduino usb debugging and an Arduino IDE compatible Board Manager.
> 26 votes

# Answer
vim can be used for Arduino development, but it will take some configuration (as is the way of vim). You'll need the syntax file and this plugin that enables you to compile and deploy from vim.

Grant Lucas produced a great write-up on getting your environment situation squared away:

> ## Using Vim for Arduino development
>
> Here's a quick post on setting up Vim for Arduino development instead of using the Arduino IDE. If you're a heavy Vim user, it can be a bit of a shock to go into a different editor. Thankfully the setup is pretty easy to get this all working with Vim. This post is assuming you are comfortable with how Vim is setup and ideally already have an environment that works for you.
>
> ### Install the Arduino IDE
>
> *Wait. What?!?* I hear you say. I know, I know. We're not actually using the Arduino IDE but we need it for some configuration and the files it installs. The Vim plugin we'll be using ties into what the IDE installs and configures so it's needed. You can download the IDE from the Arduino site.
>
> ### Install vim-arduino plugin
>
> To get the main goodness of compiling, monitoring and deploying to an Arduino, grab the latest version of vim-arduino. Install it in your .vim folder using what ever method you use to manage your Vim plugins. **Hint:** I'd recommend Pathogen as it makes installing as simple as dropping the plugin folder into a bundle folder.
>
> ### Vim syntax file
>
> Next up is to get the syntax file so we can have nice colour coding for .pde and .ino files. Download the latest arduino.vim and install it in your Vim syntax folder. To get the syntax to apply to the correct file types add the following to your vimrc file
>
> ```
> au BufRead,BufNewFile *.pde set filetype=arduino
> au BufRead,BufNewFile *.ino set filetype=arduino
>
> ```
>
> ### Configuring the Arduino IDE
>
> Before trying to compile and deploy with Vim, get it all working with the Arduino IDE first as the Vim plugin just calls from the settings saved by the IDE. If it's working in the IDE, it should work in Vim. Make sure you select the right tty.usbmodem\* serial port from Tools \> Serial Port in the IDE. **Note:** This will only show when the Arduino is plugged in.
>
> ### Working from Vim
>
> Once you can communicate with your Arduino from the IDE you should be fully good to go with Vim. You shouldn't have to open the IDE unless you want some example code. Open up your sketch file in Vim and use `<Leader>ac` to compile a sketch, `<Leader>ad` to compile and then deploy to the connected Arduino and `<Leader>as` to open a new window with `screen` to monitor the serial output from the Arduino.
> 23 votes

# Answer
You can use AVR Studio to write programs for Arduinos.

There is a plugin that lets you link against and use the arduino libraries from within Atmel Studio.

If you've used Microsoft Visual Studio, Atmel Studio is basically a reskin of Visual studio with different compiler backends that target the ATmega series of devices, so you'll feel right at home.
> 21 votes

# Answer
There is a half way solution as well since the Arduino IDE has support for external a editor, then the Arduio IDE just compiles and uploads.

Now you can use whatever IDE/editor you like to edit the code, and then you switch back to the Arduino IDE to press the compile and upload button when you are done.
> 20 votes

# Answer
One rather good IDE extension is the Arduino Mode for Emacs. It allows using a highly versatile and extensible IDE such as Emacs for writing, compiling and uploading code to the Arduino.

The documentation and instructions can be found here.
> 18 votes

# Answer
UPDATE-\> Codebender is being shut down.

There is a brilliant open source, web based IDE called Codebender

It is like Github for Arduino and has a great community working from it with thousands of examples and the dev team are exceptional.

With codebender, you can:

* program an existing sketch to your device
* clone an existing sketch
* modfy it to your needs
* share your work with the world
* embed code in your website, blog, or tutorials

Cross-platform Works on Windows, Mac & Linux, Firefox & Chrome

Codebender supports Windows (from Windows XP up to Windows 8.1, yes, even Vista :P), Mac OS X 10.6-10.9, and Linux and works within all major browsers
> 13 votes

# Answer
Majenko created and maintains UECIDE. His contributions are pretty epic; I've seen first hand his coding prowess as we worked together to get the Adafruit 1.8" TFT Joystick shield working on the chipKIT platform.
> 11 votes

# Answer
In addition to the mentioned IDEs you can use Xcode with embedXcode if you use a mac. The IDE has a great file structure and support for a lot of boards. For big and complex projects it is really good. I like to use vim or the arduino IDE for simpler and less complex sketches/projects.
> 8 votes

# Answer
There is one from Brazil called **MariaMole**: http://dalpix.com/mariamole

According to the author, like the original Arduino environment, the MariaMole facilitates the creation of software for the Arduino. However, while the original Arduino IDE has limitations to make life easier for beginners, MariaMole brings features that more advanced users are accustomed to find in professional IDEs, such as:

* Runs over Arduino install
* Workspace support multiple projects at the same time
* Multiple serial port consoles at the same time
* Files use open-formats
* Building process configurable
* Imports Arduino examples and sketches
* Easily import Arduino libraries
* Color-themes
> 8 votes

# Answer
I have always wanted to use Eclipse, since that is our standard (for Java) at work. But I never managed to get the debugger working with my AVR Dragon board - just too many layers between the source code and the chip. So I am back to using Atmel Studio. You can set the keyboard mapping to emulate various other IDEs (including Eclipse and Netbeans). I can accept the Microsft quirkiness in return for a stable debugging environment, multi-file support and professional source control features.
> 4 votes

# Answer
## PlatformIO

I use GitHub's Atom text editor with the PlatformIO package.

I like both of them:

* Atom has various useful built-in features and over 6,000 packages (which can be easily downloaded and installed from the settings pane) allowing the user to add essentially any feature he needs.
* PlatformIO is a powerful IDE for microcontroller programming. It has all the features of the Arduino IDE (like the ability to upload code to an Arduino board with one single click, a serial monitor, ...) plus many others (like all those listed by the OP) and perfectly supports Arduino. Besides "it supports more than 200 development boards along with more than 15 development platforms and 10 frameworks". It can be natively installed either on GitHub's Atom either on Microsoft's VSCode code editors.

---

**Edit**

I still use PlatformIO on Atom on a regular basis, but I just saw on their website and forum that they are discouraging users from using their Atom package while proposing PlatformIO in VSCode as a better alternative. The Atom version still works well, but if you are changing your editor and want to try PlatformIO I would suggest to follow their advice and install it in VSCode.
> 4 votes

# Answer
I use Xcode, set up as an external editor. I write everything in libraries, and the sketch simply call the libraries.
> 3 votes

# Answer
## Clion + PlatformIO

I personally use **Clion** which is a cross-platform IDE along with **PlatformIO** which is a cross platform build system for arduino and alike.

Clion because I love the jet brains IDEs. As a student or teacher you can get a free licence. And I have been told by suspicious people on the internet that there are other ways of obtaining a license (not that I would advice on doing anything like that).

PlatformIO is quite powerful and integrates well into almost any IDE. It's easy to declare dependencies to other libraries which are automatically downloaded.

I am also using the Clion serial port monitor plugin to communicate over `Serial.print()`.

With this setup you can completely ditch the old Arduino IDE which I found to be quite satisfying!
> 3 votes

# Answer
# Fritzing

> This is the new “Code View”! It lets you write your code directly inside Fritzing, and even upload it from there to your microcontroller. It even has a serial monitor. :)

Normally known as a schematic builder, Fritzing has a built in IDE.
See here for more.
> 1 votes

# Answer
Haven't seen anyone mention it yet, but I use VisualMicro for Microsoft Visual Studio (not Atmel), and I like it just fine. It gives you everything you'd normally have in Visual Studio, like intellisense typing. The trial version is the full program, and the license is pretty cheap- like 30 bucks or something. I got my work to pay for a commercial license key. Do recommend!
> 1 votes

# Answer
Notepad++

* set Notepad++: view-\>folder as work space
* and Language-\>C-\>C++ sets syntax highlighting
* set arduino Ide file-\>preferences "Use external editor"

and everything runs smoothly, without the bulk of eclipse.
> 1 votes

# Answer
My go-to choice (pun, that's only a pun, folks!) is Sloeber - Eclipse with Jantje's EclipseArduino plugin. Having decades of emacs muscle-memory-training, I use MulgaSoft's Emacs+ plugin with it, switching to real GNU emacs for the heavy lifting - as developing a project and new libraries for it in parallel, f/ex, and use Sloeber to catch my typos & brain-f\*ts.
> 1 votes

# Answer
A good alternative to the Arduino IDE is Visual Studio Code in combination with the Microsoft extension for Arduino https://github.com/Microsoft/vscode-arduino

It gives all the features of the Arduino IDE such as

Verify and upload your sketches in Visual Studio Code

* Built-in board and library manager
* Built-in example list
* Built-in serial monitor

but additionally to offers some attractive features:

* IntelliSense and syntax highlighting for Arduino sketches
* Snippets for sketches
* Automatic Arduino project scaffolding
> 1 votes

# Answer
I use Eclipse and Sublime Text for editing Arduino code, and I build in the Arduino IDE with it set to "external editor" mode, or using the Arduino Command Line tools. Eclipse has a fantastic indexer and makes understanding the Arduino core much easier. I've written a detailed PDF about using and setting up Eclipse for professional software development, incl for Arduino, here: https://github.com/ElectricRCAircraftGuy/eRCaGuy\_dotfiles/blob/master/eclipse/Eclipse%20setup%20instructions%20on%20a%20new%20Linux%20(or%20other%20OS)%20computer.pdf.

Note that I'm using regular Eclipse for C/C++, with no Arduino plugins. I don't find them that useful since they can never seem to keep up with the latest Arduino build tools anyway.

See my document for full setup information in general.

# Related:

1. C++ vs. The Arduino Language?
> 1 votes

# Answer
after some experience

any editor (atom or vscode) are excellent with platformIO

offering:

1. syntax highlighting
2. debugger
3. easy project (s) manager
4. (which i like most) collapsible blocks
> 0 votes

# Answer
In late 2019 we have the Deviot Sublime Text 3 plugin that runs on top of PlatformIO.
> 0 votes

---
Tags: programming, arduino-ide, c++, ide
---


# Question
Title: Convert comma-delimited Arduino String of hex values to array of bytes
My apologies if this is a naive question. How do I convert a `String` which has hex values to a byte array that has those hex values?

This:

```
String s = "0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff";

```

Needs to be converted to this:

```
char test[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };

```

I used the following procedure. It does convert it, however, each character is saved as a character as opposed to hex value:

```
unsigned int str_len = s.length() + 1;
char charArray[str_len];
s.toCharArray(charArray, str_len);

```

Any help will be appreciated. Thank you!

# Answer
> 3 votes
You only convert the String object to a char array. It need to further split the char array into substring, and then convert it to number.

To split the char array, you can use strtok() function in c++ to do the job.

There is no str conversion function that can convert `"0xff"` into `uint8_t` directly. However, as @rubemnobre mentioned strtol() can be used to convert a c string to a `long` (in Arduino, it is 4-byte number) and further cast into a `uint8_t` and store in a byte array.

```
String s = "0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff";

// Convert String object to char array
unsigned int str_len = s.length()+1;
char charArray[str_len];
s.toCharArray(charArray, str_len);

uint8_t byteArray[7];
int i=0;

// split charArray at each ',' and convert to uint8_t
char *p = strtok(charArray, ",");
while(p != NULL) {
  byteArray[i++] = strtoul(p, NULL, 16);
  p = strtok(NULL, ",");
}

// Print the byteArray
for (i=0; i<sizeof(byteArray)/sizeof(char); i++) {
  Serial.print(byteArray[i]);
  Serial.println(", ");
}
Serial.println();

```

# Answer
> 2 votes
There are C functions that can convert text to number. For example, `strtol()` or `atoi()`. Here is a little snippet to get you started:

```
char *str = "FF";
char *ptr;
int result = strtol(str, &ptr, 16); //the 16 is the base the string is in (HEX -> base 16)

```

`result` will have `0xFF` or `255` by the end. You can use this to achieve what you are trying to do. Take a look at this for functions you can use to manage your `String`.

---
Tags: arduino-nano, string
---


# Question
Title: Arduino Nano, DS3231 RTC clock module and 4 cascaded FC-16 led matrix modules
Like I said in the title, I am using a DS3231 real time clock module and 4 cascaded FC-16 modules(they are basically MAX7219 led matrices based modules). My goal is to display a timetable, a schedule for a classroom on the matrices. The purpose of the DS3231 module is to keep track of time(mainly hours) from 8:00AM to 20:00PM, to display the hour on the matrix and to change the subject when it hits even hours. Eg: when it's 8:00AM we have subject A, when it's 10:00AM we have subject B etc

And after that I have to use a ESP8266 wifi module to change the schedule from distance.

EDIT1: I managed to display the hour on the matrix, but now I really can't figure out how to display the text in 4 rows. I have 4 FC-16 modules and I want to put each of them on top of the other so I can have 4 rows of text. I managed to do this by inserting space between words but this is not optimal. I want this to be automated so the person changing the text in the program doesn't have to do the spacing thing by themselves.

<pre><code>#include "RTClib.h"
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>

const uint16_t WAIT_TIME = 1000;

#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
#define MAX_DEVICES 16

#define CLK_PIN   13
#define DATA_PIN  11
#define CS_PIN    10

MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);

RTC_DS3231 rtc;

//char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {
  P.begin();

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

 if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
//     If the RTC have lost power it will set the RTC to the date & time this sketch was compiled in the following line
   rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

  }
}

void loop () {
    DateTime now = rtc.now();

    char buffer[] = "hh:mm";  // hours and minutes
    P.print(now.toString(buffer));  // display

   // Serial.println();
    delay(1000);
}```
</code></pre>

# Answer
> how do I display the time from the DS3231 clock module on the FC-16 led matrix modules?

You can use the `DateTime::toString()` method to convert the current time to a string in the format of your choice, then `P.print()` to display that string on the LED matrix:

```
void loop() {
    DateTime now = rtc.now();
    char buffer[] = "hh:mm";  // hours and minutes
    P.print(now.toString(buffer));  // display
}

```

> how do I use that hour of the day so that the microcontroller knows what text it should display next?

Condition your logic on `now.hour()`.
> 0 votes

---
Tags: esp8266, programming, interrupt, max7219, ds3231-alarms
---


# Question
Title: Boost an audio signal for analog read - Envelope Detector
I'm working on my first Arduino project and I have a sensitivity issue.

I'm building a module to listen to an audio signal and to start the power source of my speaker with a relay. Everything seems to work fine, but if I drop the volume of my sound, the analog pin doesn't record values (at maximum volume, it peaks at around 50, which is not a lot).

I thought about getting a capacitor but I'm really not sure on what I should get and how the wiring should be done.

# Answer
it sounds like what you are wanting to do is to detect a minimum threshold of sound so that your speaker power source can be turned on when an audio signal is playing.

You need to amplify your signal while also avoiding voltages that exceed the maximum input specification and also don't go negative. One way to accomplish this is with an operational amplifier (op-amp) circuit. A specific type will accomplish all three requirements. An op-amp that is powered by a single-sided supply, for example +5V and ground, will prevent negative voltages and limit the maximum voltage exceeding what the Arduino can take.

For your application, you don't really care about making a high-quality audio amplifier. You care about not distorting the signal (music) that you are monitoring and detecting a threshold level. Op-amps are good because they have high impedance inputs (they don't draw much (or any) current from your music signal) and they work with few external components.

A classic text for learning about electronics is Horowitz and Hill. Alternatively, you can find references for circuit designs on-line with appropriate searches. For any op-amp that you buy, you can get a datasheet that tells you how to use it. The following reference goes into detail (maybe too much) about single supply op-amps.

Circuits (and search terms) that you might find useful are op-amp follower, single supply, bias, and capacitive coupling. You'll need to purchase components. A good supplier is DigiKey. DigiKey has an on-line catalog that allows you to do a parametric search to identify the components that you need. You'll need a breadboard, resistors, capacitors, and the op-amp in a dual-inline package (DIP).

One search filters the list of possibilities from tens of thousands to a reasonable number. The LM833 Datasheet here is a reasonable choice.

Test equipment, like a single generator and oscilloscope can be very helpful when building amplifiers. You might be able to digitize your amplified signal with your Arduino if you don't have access to test equipment.
> 1 votes

# Answer
What you're looking for is called a peak detector, or probably better in your case - an envelope detector. Pass this through an op-amp with adjustable gain to let you tune your sensitivity. R3 - your potentiometer will let you adjust the sensitivity.Your gain will be

.

Set Vdd to 5V and common ground with your Arduino.

It's unlikely your audio source is generating too much voltage given you're saying its not registering - but in the unlikely event you're above 5V put a reverse biased Zener diode in parallel with your capacitor to clamp voltage to 5V

simulate this circuit – Schematic created using CircuitLab

Hit simulate to see what playing with values does!
> 1 votes

---
Tags: audio, analog
---


# Question
Title: What is the equivilent of PORTx for Teensy (4.0)?
I've seen people use code like `PORTB |= 0x1 << 6` to set the sixth bit of PORTB in arduino. I understand that this is significantly faster than using `digitalWrite`. How can this be done using a modern Teensy (i.e. 3.6 or 4.0) if at all?

# Answer
All Teensies support digitalWriteFast out of the box. digitalWriteFast compiles to just setting the bit in the right port register. You can not do that faster by direct register manipulation.

However, if for some reason you do want to manipulate the registers directly here the pin/gpio relation for the T4. (Generated by the sketch described here: https://github.com/luni64/TeensyTimerTool/wiki/Avoid-PWM-timer-clashes")

```
Pin |  GPIO Reg  |  PWM timer
----|------------|-------------
00  |  GPIO6_03  |  FLEX_PWM1
01  |  GPIO6_02  |  FLEX_PWM1
02  |  GPIO9_04  |  FLEX_PWM4
03  |  GPIO9_05  |  FLEX_PWM4
04  |  GPIO9_06  |  FLEX_PWM2
05  |  GPIO9_08  |  FLEX_PWM2
06  |  GPIO7_10  |  FLEX_PWM2
07  |  GPIO7_17  |  FLEX_PWM1
08  |  GPIO7_16  |  FLEX_PWM1
09  |  GPIO7_11  |  FLEX_PWM2
10  |  GPIO7_00  |  QUAD1
11  |  GPIO7_02  |  QUAD1
12  |  GPIO7_01  |  QUAD1
13  |  GPIO7_03  |  QUAD2
14  |  GPIO6_18  |  QUAD3
15  |  GPIO6_19  |  QUAD3
16  |  GPIO6_23  |  no pwm
17  |  GPIO6_22  |  no pwm
18  |  GPIO6_17  |  QUAD3
19  |  GPIO6_16  |  QUAD3
20  |  GPIO6_26  |  no pwm
21  |  GPIO6_27  |  no pwm
22  |  GPIO6_24  |  FLEX_PWM4
23  |  GPIO6_25  |  FLEX_PWM4
24  |  GPIO6_12  |  FLEX_PWM1
25  |  GPIO6_13  |  FLEX_PWM1
26  |  GPIO6_30  |  no pwm
27  |  GPIO6_31  |  no pwm
28  |  GPIO8_18  |  FLEX_PWM3
29  |  GPIO9_31  |  FLEX_PWM3
30  |  GPIO8_23  |  no pwm
31  |  GPIO8_22  |  no pwm
32  |  GPIO7_12  |  no pwm
33  |  GPIO9_07  |  FLEX_PWM2
34  |  GPIO8_15  |  FLEX_PWM1
35  |  GPIO8_14  |  FLEX_PWM1
36  |  GPIO8_13  |  FLEX_PWM1
37  |  GPIO8_12  |  FLEX_PWM1
38  |  GPIO8_17  |  FLEX_PWM1
39  |  GPIO8_16  |  FLEX_PWM1

#### Sorted by PWM timer
Pin |  GPIO Reg  |  PWM timer
----|------------|-------------
12  |  GPIO7_01  |  QUAD1
11  |  GPIO7_02  |  QUAD1
10  |  GPIO7_00  |  QUAD1
13  |  GPIO7_03  |  QUAD2
18  |  GPIO6_17  |  QUAD3
15  |  GPIO6_19  |  QUAD3
14  |  GPIO6_18  |  QUAD3
19  |  GPIO6_16  |  QUAD3
24  |  GPIO6_12  |  FLEX_PWM1
01  |  GPIO6_02  |  FLEX_PWM1
25  |  GPIO6_13  |  FLEX_PWM1
34  |  GPIO8_15  |  FLEX_PWM1
35  |  GPIO8_14  |  FLEX_PWM1
36  |  GPIO8_13  |  FLEX_PWM1
37  |  GPIO8_12  |  FLEX_PWM1
38  |  GPIO8_17  |  FLEX_PWM1
39  |  GPIO8_16  |  FLEX_PWM1
00  |  GPIO6_03  |  FLEX_PWM1
08  |  GPIO7_16  |  FLEX_PWM1
07  |  GPIO7_17  |  FLEX_PWM1
09  |  GPIO7_11  |  FLEX_PWM2
04  |  GPIO9_06  |  FLEX_PWM2
05  |  GPIO9_08  |  FLEX_PWM2
06  |  GPIO7_10  |  FLEX_PWM2
33  |  GPIO9_07  |  FLEX_PWM2
28  |  GPIO8_18  |  FLEX_PWM3
29  |  GPIO9_31  |  FLEX_PWM3
23  |  GPIO6_25  |  FLEX_PWM4
22  |  GPIO6_24  |  FLEX_PWM4
03  |  GPIO9_05  |  FLEX_PWM4
02  |  GPIO9_04  |  FLEX_PWM4
27  |  GPIO6_31  |  no pwm
17  |  GPIO6_22  |  no pwm
26  |  GPIO6_30  |  no pwm
30  |  GPIO8_23  |  no pwm
31  |  GPIO8_22  |  no pwm
32  |  GPIO7_12  |  no pwm
21  |  GPIO6_27  |  no pwm
20  |  GPIO6_26  |  no pwm
16  |  GPIO6_23  |  no pwm

#### Sorted by GPIO register:
Pin |  GPIO Reg  |  PWM timer
----|------------|-------------
01  |  GPIO6_02  |  FLEX_PWM1
00  |  GPIO6_03  |  FLEX_PWM1
24  |  GPIO6_12  |  FLEX_PWM1
25  |  GPIO6_13  |  FLEX_PWM1
19  |  GPIO6_16  |  QUAD3
18  |  GPIO6_17  |  QUAD3
14  |  GPIO6_18  |  QUAD3
15  |  GPIO6_19  |  QUAD3
17  |  GPIO6_22  |  no pwm
16  |  GPIO6_23  |  no pwm
22  |  GPIO6_24  |  FLEX_PWM4
23  |  GPIO6_25  |  FLEX_PWM4
20  |  GPIO6_26  |  no pwm
21  |  GPIO6_27  |  no pwm
26  |  GPIO6_30  |  no pwm
27  |  GPIO6_31  |  no pwm
10  |  GPIO7_00  |  QUAD1
12  |  GPIO7_01  |  QUAD1
11  |  GPIO7_02  |  QUAD1
13  |  GPIO7_03  |  QUAD2
06  |  GPIO7_10  |  FLEX_PWM2
09  |  GPIO7_11  |  FLEX_PWM2
32  |  GPIO7_12  |  no pwm
08  |  GPIO7_16  |  FLEX_PWM1
07  |  GPIO7_17  |  FLEX_PWM1
37  |  GPIO8_12  |  FLEX_PWM1
36  |  GPIO8_13  |  FLEX_PWM1
35  |  GPIO8_14  |  FLEX_PWM1
34  |  GPIO8_15  |  FLEX_PWM1
39  |  GPIO8_16  |  FLEX_PWM1
38  |  GPIO8_17  |  FLEX_PWM1
28  |  GPIO8_18  |  FLEX_PWM3
31  |  GPIO8_22  |  no pwm
30  |  GPIO8_23  |  no pwm
02  |  GPIO9_04  |  FLEX_PWM4
03  |  GPIO9_05  |  FLEX_PWM4
04  |  GPIO9_06  |  FLEX_PWM2
33  |  GPIO9_07  |  FLEX_PWM2
05  |  GPIO9_08  |  FLEX_PWM2
29  |  GPIO9_31  |  FLEX_PWM3

```
> 5 votes

---
Tags: pins, teensy, port-mapping, digitalwrite
---


# Question
Title: Trying to do hello world app for Nokia 5110 LCD with arduino yun and johnny five
I have a Nokia 5110 LCD which is using this display `PCD8544`, I am using a arduino yun and johnny five I have hooked up the following pins. So far with my node app all that happens is the lcd lights up. I am not sure if maybe the lcd is not supported with johnny five, if I have a pin wrong. I followed this site for the pin setup https://lastminuteengineers.com/nokia-5110-lcd-arduino-tutorial/ Any help would be greatly appreciated. This is my first attempt with Johnny five and second attempt at hooking anything up to a bread board. Hope we can get this working. Thanks

Here is my code

```
const five = require('johnny-five');
const board = new five.Board();

board.on("ready", function() {

    lcd = new five.LCD({
      controller: "PCF8574"
    });

    lcd.print("Hello");
  });

```

Here is my configuration

```
blue         =  pin 7          sclk     (serial clock(CLK)) 10 om
white        =  pin 6          DN(MOSI) (Serial data in) 10om
grey         =  pin 5          D/C      (Mode select) 10om
orange       =  pin 4          RST      (Reset) 10om
yellow/red   =  pin 3          SCE      (Chip select) 10om
yellow-short =  power strip +  LED      (backlight supply) 1kom
green/black  =  gnd / strip -
blue/power   =  3.4v power + 330om

```

Here is are some images of the setup

Update so my configuration looks more like this now

```
blue         =  pin 7          sclk     (serial clock(CLK)) 10k
white        =  pin 6          DN(MOSI) (Serial data in) 10k
grey         =  pin 5          D/C      (Mode select) 10k
orange       =  pin 4          RST      (Reset) 10k
yellow/red   =  pin 3          SCE      (Chip select) direct
yellow-short =  power strip +  LED      (backlight supply) 330
green/black  =  gnd / strip -
blue/power   =  3.4v power powerstrip direct

```

# Answer
> 1 votes
Arduino Yun is a ATMega32U4-based board, like other ATMega32U4-based Arduino boards, such as Arduino Leonardo, Micro, the SPI is only available on the ICSP header:

```
MOSI - Yun has it on ICSP Pin 4
MISO - Yun has it on ICSP Pin 1
SCK - Yun has it on ICSP pin 3
SS - Yun has no dedicated pin, use any digital data pin

```

You can find out the ICSP header pin assignment at Arduino SPI reference page. So here is the connection between Arduino Yun and LCD5110

```
Yun               LCD 5110
ICSP pin3         CLK(SCK)
ICSP pin 4        DN(MOSI)
any GPIO pin      D/C (see note 1)
RST               RST
any GPIO pin      SCE(SS) (see note 1)
any GPIO pin      Backlight (via a 330 ohm resistor) (see note 2)
GND               GND
3v3               VCC

```

> Note 1: Although you could use any GPIO for D/C and SCE, you should consult the library that you are using to see what pin the library used for the data/command line and SS line.
>
> Note 2: Connecting to a GPIO pin allows you to turn on and off the LED backlight, you could ignore the connection if you don't want the backlight, or you could connect it directly to 3v3 via a resistor if you want backlight on permanently

If you still have problem in using the LCD5110, please update your question with complete code and the library that you are using.

---
Tags: lcd, arduino-yun, print, johnny-five
---


# Question
Title: ATtiny85 - report error "Device reports version as: 2.2"
I've bought ATtiny, from see link. Trying to upload a basic `Blink` sketch I get this error: `Device reports version as: 2.2`.

1) Board manager was updated using `http://digistump.com/package_digistump_index.json`

2) Board selected as `Digispark (Default -16.5MHz )`

3) Programmer set to `Micronocleus`

Tried using some guides on-line, but some were old, some were for windows, while I'm using Ubuntu machine.

Appreciate any help, Guy

# Answer
> 1 votes
It sounds like you have a newer board than the version of Micronucleus in the Arduino package.

As I discovered here you basically need to upgrade micronucleus in your Ardino installation, which you can download from here

* Download the zip file from Github and extract it. Then in a terminal (if you're not already in one) go to the directory you extracted.
* Build the executable by typing "make"
* Copy the compiled executable to `~/.arduino15/packages/digistump/tools/micronucleus/<version>/`

where `<version>` is the currently installed version number (e.g., `2.0a4`). There should already be a `micronucleus` executable in there that you would replace with your newly compiled one.

---
Tags: bootloader, attiny
---


# Question
Title: Is it possible to overload the digital pins for an Arduino?
I worked on an Arduino project for school that was a self-driving security robot that also acted as a smart home system.

It was essentially a self-driving Roomba-like car that included several LED's(resembling home appliances), three distance sensors, an LCD screen, a motion sensor, an audio amplifier with a speaker, an SD card module to store .wav files, a Bluetooth module to connect with MIT App Inventor, and a motor driver that controlled two electric motors. It's a long list of modules so the Arduino Mega was required. When assembling all of these modules and building the code, I would perform intermittent tests that would isolate the obstacle avoidance and driving, turning on appliances(LED's), and sending and receiving data from the phone app. Every aspect of the project worked in isolation until I combined everything.

When everything was combined, instead of simply driving forward until an obstacle is detected as its programmed, the car would jitter around and not react to walls or obstacles. Also, the LCD screen was heavily dimmed as opposed to when the Arduino was running off of laptop power. Especially when the phone app called for turning on heat or AC, the proper LED's would turn on, but the whole system seemed to respond to the initial load required to read a .wav file and play the corresponding audio and made the jitter worse.

So my question is this, with all these modules plugged into an Arduino, is it possible that the number of modules all needing some input from the digital pins has highlighted a current limitation? All of these issues were exacerbated when the laptop power was replaced with a 9v battery. I was able to confirm that the code was not the issue as I would simply comment out major portions but leaving all the pins initialized. Also, if there is a current output limitation, is there any way to explain why? Thank you for reading my lengthy post and for giving feedback.

# Answer
> 2 votes
As mentioned in the comments, you cannot power your robot from a 9V block battery. These are made for low power projects (like a smoke detector) and cannot provide enough current to drive even only the motors correctly. Using 2 of them does not really help much. You need to change to a different battery type. If you want to stay with alkalines, you could use six AA batteries or C cells, like jsotola suggested. But you might want to upgrade to a fitting LiPo/LiIon battery (in combination with a fitting battery charger module). That would give you enough power for all your needs, while being rechargable.

A different issue: It seems to be, that you provide all the components (sensors and motors) with power through the 5V pin of the Arduino. But especially with motors you can easily reach the current limitation of the voltage regulator on the Arduino. When drawing more current through it, than recommended, the regulator will go in emergency shutdown (with a genuine Arduino; with the cheap clones, the regulator will melt and be destroyed).

Instead you need to be sure, that the drawn current does not exceed the maximum current for the voltage regulator (depends also on the voltage provided). At least the motors should be provided with power parallel to the Arduino, so that the motor current will not flow through the Arduino. It is unclear, how you are controlling the motors. If you are using a motor shield, then look for the terminal for external power supply on it. Most motor shields have them. Depending on the batteries, you will use in future, and on motors and shield, you maybe an directly connect the battery voltage to the shield. Or you need to buy an extra (switching) voltage regulator, which brings the battery voltage down to 5V. In that case be sure, that the regulator can provide the needed current plus some overhead clearance.

---
Tags: arduino-mega, power, current, digital, project-critique
---


title: Keyboard.print() skips keys

text:
# Question
Title: Keyboard.print() skips keys
I'm playing with the Arduino Leonardo `Keyboard.print()` command, but I'm facing a annoying problem:

When I print a double quote, it will not appear and also will make to disappear the next character (i.e.):

```
Keyboard.print("echo \"This is a demo\"");

```

Output:

```
echo his is a demo

```

And when I use this line:

```
Keyboard.print("echo -This is \"a demo-");

```

Output (note the umlaut over the `a` instead of getting `"a`):

```
echo 'This is ä demo'

```

I suspect that the problem is that my computer is configured to use Spanish layout.

What source code file can I change to fix this? I can't find the defines used by `Keyboard.print()`

# Answer
> 1 votes
In your particular case, the double quote ***is to be entered*** (using the Spanish keyboard layout) by `Shift` \+ the physical key labelled `2`. On a US keyboard, `Shift` \+ the physical key labelled `2` is "@".

Thus, this simply will get the desired result (the Arduino library assumes a US keyboard layout):

```
Keyboard.print("echo @This is a demo@");

```

### More general solution

More generally, strings can be encoded as in the following table (the exact mappings depend on the particular keyboard layout - this will work for many European keyboard layouts).

If the *physical key* (and modifier key, if any) *exists* on the US keyboard to get the character typed out using the non-US keyboard layout, then this method works fine.

```
To get   Use   Notes
--------------------------------------------
;        <     Will result in Shift action
:        >     Will result in Shift action
(        *     Will result in Shift action
)        (     Will result in Shift action
/        &     Will result in Shift action
?        _     Will result in Shift action
=        )     Will result in Shift action
&        ^     Will result in Shift action

-        /
+        -
_        ?

"        @     Will result in Shift action

,        ,     The same
.        .     The same
#        #     The same

```

### Even more general solution

Even more generally, some keys are not on the US keyboard (e.g. the 102th key on European keyboards for the original PC keyboards, often with `<`, `>`, `\`, and `|`), and it is ***not*** possible to use Keyboard.print().

Instead, use the low-level HID().SendReport() function - with code 100 (decimal) for the first parameter for the 102th key. See the library source code, Keyboard.cpp (/libraries/Keyboard/src/Keyboard.cpp), for how to use HID().SendReport().

### Alternative solution

Some operating systems enable entering characters using the keyboard and a numeric code.

This is at the expense of making it operating-system dependent (but making it independent of the active keyboard layout).

For example, `Ctrl` \+ `Shift` \+ `U` on Linux (GUI only, dependent on the window manager(?)). For the particular problem (the Unicode code point for `"` is *0022*), without any functional abstraction to reduce the redundancy:

```
Keyboard.print("echo ");

Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.press('u');
Keyboard.releaseAll();
Keyboard.print("0022");
Keyboard.press(KEY_RETURN);
Keyboard.releaseAll();

Keyboard.print("This is a demo");

Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.press('u');
Keyboard.releaseAll();
Keyboard.print("0022");
Keyboard.press(KEY_RETURN);
Keyboard.releaseAll();

```

Unicode code points can be found at unicode-table.com.

### Media keys

Even though the media keys are listed in the table (e.g. code 128 for "Volume Up" on page 53), they do not work using the method described in the previous section. But there is a solution.

### Platform

This was tested with:

* Arduino Leonardo
* The Spanish keyboard layout was added to the Linux settings and activated. There were 14 different ones to choose from, but I used the one labelled "Spanish". It was verified that "@" actually resulted in an output of "`"`". It was also verified that the `Ctrl` \+ `Shift` \+ `U` method worked.
* Linux, Ubuntu 19.10 (Eoan Ermine), but with the buggy GNOME replaced by Cinnamon.
* 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

# Answer
> 4 votes
The Arduino assumes a US keyboard layout. The thing with keyboards is they don't actually send the letters or symbols that are printed on the keys. Instead the send a *scan code* that defines *where* on the keyboard the key is. It is then up to the computer to convert those scan codes into actual letters and symbols, and that is performed by the keyboard mapping selected in the operating system.

Some special keys are known as *dead keys*. These don't actually print a character on their own - instead they are used to modify the next key pressed - for instance the key which occupies the space a " would be on a US keyboard, on a Spanish keyboard, is a dead key which modifies the next key by adding an umlaut to it.

Since the Arduino doesn't know that you have a Spanish mapping, when you send a " it just sends what it believes is the location of that character on a keyboard, and of course it gets that wrong since it assumes the wrong keyboard layout.

So there are two things you can do to "fix" it:

1. Change your keyboard layout to US, but that will mean your normal keyboard will stop working properly.
2. Change how the Arduino thinks the keyboard is laid out, but that means lots of work to find the right scan codes.

The Arduino's keyboard layout is stored in the file `HID.cpp` in the Arduino core (`hardware\avr\cores\arduino` or somewhere like that - I forget off hand) and is the `_asciimap` array. It is a list of the first 128 ASCII characters and the keyboard scancode mappings for them, including *modifier keys* like Shift. You will have to find the scan codes for the keys you want to map on your keyboard layout and change the codes in that list. For instance, the character " is listed as:

```
0x34|SHIFT,    // "

```

Which is scan code 0x34 (52 decimal) coupled with the SHIFT modifier. You will have to discover (maybe Google can help) what the 0x34 should be changed to so that it moves the " to wherever it is on a Spanish keyboard.

---
Tags: usb, arduino-leonardo, keyboard, atmega32u4
---


# Question
Title: FC-16 led matrix module based on MAX7219
EDIT:

```
const char  *pc[NUM_ZONES] =
{
  "ROOM", //0
  "SUBJECT", //1
  "GRADE",//2
  };

```

I did this and I can't get them to display every row simultaneously.

```
void loop(void)
{

 DateTime now = rtc.now();
 char buffer[] = "hh:mm";  // hours and minutes

 for (uint8_t i=0; i<NUM_ZONES; i++){
   P.displayZoneText(0,now.toString(buffer), PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
   P.displayZoneText(1, pc[1], PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
   P.displayZoneText(2, pc[2], PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);  // display
   P.displayZoneText(3, pc[3], PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
 }
}

```

I can only display one row at a time like this, now it only displays the hour:min.

Tell me what am I doing wrong

EDIT2:

Or like this:

-this is my goal, to change the text based on hour

```
void loop(void)
{

 DateTime now = rtc.now();
 char buffer[] = "hh:mm";  // hours and minutes

   P.displayZoneText(0,now.toString(buffer), PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);

   if(now.hour()==21){
   P.displayZoneText(1, pc[1], PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
   P.displayZoneText(2, pc[2], PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);  // display
   P.displayZoneText(3, pc[3], PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
   }
   P.displayAnimate();
}

```

And at the moment with this code it only displays the hour and minutes

# Answer
> 0 votes
I haven't used this library, but reading through the documentation it seems it operates on the concept of zones.

1. Create a zone for each row (a zone is a contiguous block of modules forming a kind of sub-display)
2. Perform operations on the zones with the zone-specific functions.

For example, setting up your zones would be:

```
P.begin(4); // We will have 4 zones
P.setZone(0, 0, 3); // Modules 0-3 in zone 0
P.setZone(1, 4, 7); // Modules 4-7 in zone 1
P.setZone(2, 8, 11); // Modules 8-11 in zone 2
P.setZone(3, 12, 15); // Modules 12-15 in zone 3

```

Then you can clear a zone with:

```
P.displayClear(2); // Clear zone 2

```

And write text to a zone with:

```
P.displayZoneText(3, "P03", PA_CENTER, 0, 0, PA_NO_EFFECT, PA_NO_EFFECT);

```

I'm not certain about what all the parameters mean, but the prototype is:

```
void displayZoneText(uint8_t z, const char *pText, textPosition_t align, uint16_t speed, uint16_t pause, textEffect_t effectIn, textEffect_t effectOut = PA_NO_EFFECT);

```

---
Tags: arduino-uno, programming, arduino-nano, display, max7219
---


title: i2c wire length

text:
# Question
Title: i2c wire length
I have some problems with i2c. I can not use long wires on SDA and SCK bus.

This seems to be the consequence of the capacity between the SDA and SCK wires and not between SDA/SCK and GND.

I figured this out by placing capacitors in a breadboard with a Arduino UNO and some MCP23017's (with 2k2 pull-up resistors).

100pF capacitor between SDA and SCK: No problem.

150pF: The communication stops.

1nF from SDA to GND and/or 1nF from SCK to GND: No problem.

A two wire cable is approx 50pF per meter, so 2 meters seems the limit.

With an ATtiny85 (8MHz clock, 100k i2c speed) as master it is even worse: With 2k2 pull-up a capacity of 68pF is killing.

By reducing the pull-up resisters to 470E I was able to go up to 200pF (hurray: 4 meters of wire).

Someone any idea how to increase the distance by tuning the SDA/SCK timing?

# Answer
> 3 votes
As @majenko wrote, the I2C bus was not designed to go over wires or into a cable. It is ment for components on the same pcb board. As @mikaelpatel wrote there are bus drives which convert the I2C signal into some kind of RS-485 signal for twisted pair cables.

The crosstalk between SDA and SCL should be avoided at all times. Don't put SDA and SCL into wires that are next to each other. When using twisted pair cable (for example Cat5), then use SDA in a different pair than SCL.
The worst situation is when SDA and SCL are next to each other in a flat ribbon cable.

The capacitance caused by the cable from SDA to GND and from SCL to GND can be compensated some by a lower value of the pullup resistors and by lowering the clock speed.

The maximum current is specified as 3 mA. That means with 5V, the lowest value for the pullup resistor is 1k6.
A little more can be achieved with a current driver of 3 mA instead of the pullup resistors. This is not often done, but it creates a better signal.

The Arduino Wire library for the Arduino Uno can be set to 50 kHz with Wire.setClock. I don't know the lowest value, but there is a limit without warning. I don't know the lowest clock speed for an Attiny microcontroller. A software I2C bus implementation can often go much lower.
*Note that some sensors have a minimum clock speed.*

The rule of thumb is that 50 cm is the maximum for the I2C wires. However, some say that they are able to use the normal I2C bus over 6 meters cable. My opinion is that the I2C should always work, since it is not very fault tolerant, and the Arduino Wire library for the Arduino Uno is not fault tolerant at all. Therefor, don't go near the limits.

The MultiSpeedI2CScanner (probably only working for Atmega chips) helped me a lot to learn about the I2C limits in different situations.

# Answer
> 1 votes
With 2 shielded cables, separate for SDA, SCL no problem to go several meters.

I just connected 2 I2C devices on common shielded cables 6m long SDA, SCL 3.3V and GND on non-shielded cables

Successfully tried also computer mice shielded cables, it's about 1.5m working no problem

Pull up resistors approx. 4k7

---
Tags: i2c, attiny85
---


title: UNIX time in ms to human date time

text:
# Question
Title: UNIX time in ms to human date time
Been struggling with something for a few days.

Loading data from a website via JSON and it includes an updated date time in milliseconds. This is an EPOCH date and I can get the right value using some of the online convertor sites, epochconvertor.com

That said when I try and parse it in my sketch it’s not retuning the correct date.

JSON “currentupdatedms”:1588312648603

Convertor Shows as: 1 May 2020 05:57:28.603

My sketch is showing: 1 May 2020 02:33:00

That’s in the JSON and I can’t use a Long as it’s 13 digits. Tried Long Long and it accepts the value but when I later divide by 1000 to get seconds the number changes completely when I try printing it to serial or the OLED.

Plan is to use the Timeh library to display it as a human date time.

Any thoughts be appreciated.

Here is my code and I have tried various methods:

```
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#include <TimeLib.h>
#include <time.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

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

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#define ARDUINOJSON_JSON_LONG_LONG 1 //Not needed???
#define   ONE_HOUR   3600
const size_t capacity = JSON_OBJECT_SIZE(8) + 140;
DynamicJsonDocument doc(capacity);

/*Notes
   Need to look at conversion of Update and Changed times as they are not showing correctly
   Move the conversion of time datetime in ms to a seperate function
   Move the get request and JSON section to seperate function
*/

const char* ssid = "SSID";
const char* password = "PWD";

void setup () {

  Serial.begin(4800);

  Wire.begin(2, 0);           // set I2C pins (SDA = GPIO2, SCL = GPIO0), default clock is 100kHz

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;); // Don't proceed, loop forever
  }

  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);

  WiFi.begin(ssid, password);

  display.setCursor(0, 0);
  display.println(F("Connecting to Wifi..."));
  display.display();

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to Wifi...");
  }

  display.setCursor(0, 10);
  display.println(F("Wifi Connected..."));
  display.display();
}

void loop() {

  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status

    display.setCursor(0, 20);
    display.println(F("Requesting Data..."));
    display.display();
    delay(2000); // Pause for 2 seconds

    HTTPClient http;  //Declare an object of class HTTPClient

    http.begin("http://corona.tuply.co.za/DataHandler.ashx?w=s&uq=8f1fp8p5jdxi84481");  //Specify request destination
    int httpCode = http.GET();                                                                  //Send the request

    if (httpCode > 0) { //Check the returning code

      String payload = http.getString();   //Get the request response payload
      Serial.println(payload);                     //Print the response payload

      deserializeJson(doc, payload);

      int TotalCases = doc["TotalCases"];
      int TotalCasesToday = doc["TotalCasesToday"];
      int TotalDeaths = doc["TotalDeaths"];
      int TotalDeathsToday = doc["TotalDeathsToday"];
      int TotalRecovered = doc["TotalRecovered"];
      int TotalTerritories = doc["TotalTerritories"];
      long long CurrentUpdatedMS = doc["CurrentUpdatedMS"];
      long long CurrentChangedMS = doc["CurrentChangedMS"];

      //delay(10000);

      time_t CurrentUpdateMS_t = (CurrentUpdatedMS/1000) + ONE_HOUR; //ONE_HOUR added for BST

      char buffUpdateMS[32];
      sprintf(buffUpdateMS, "%02d/%02d/%02d %02d:%02d:%02d", day(CurrentUpdateMS_t), month(CurrentUpdateMS_t), year(CurrentUpdateMS_t), hour(CurrentUpdateMS_t), minute(CurrentUpdateMS_t), second(CurrentUpdateMS_t));
      Serial.print("U:");
      Serial.println(buffUpdateMS);
      Serial.print("ctime: ");
      Serial.println(ctime(&CurrentUpdateMS_t));

      time_t CurrentChangedMS_t = CurrentChangedMS/1000 + ONE_HOUR; //ONE_HOUR added for BST

      char buffChangedMS[32];
      sprintf(buffChangedMS, "%02d/%02d/%02d %02d:%02d:%02d", day(CurrentChangedMS_t), month(CurrentChangedMS_t), year(CurrentChangedMS_t), hour(CurrentChangedMS_t), minute(CurrentChangedMS_t), second(CurrentChangedMS_t));
      Serial.print("C:");
      Serial.println(buffChangedMS);
      Serial.print("ctime: ");
      Serial.println(ctime(&CurrentChangedMS_t));

      display.clearDisplay();

      display.setCursor(0, 0);
      display.print(F("T Cases: "));
      display.println(TotalCases);

      Serial.print("Total Cases: ");
      Serial.println(TotalCases);

      Serial.print("Total Cases Today: ");
      Serial.println(TotalCasesToday);

      display.setCursor(0, 10);
      display.print(F("T Deaths: "));
      display.println(TotalDeaths);

      Serial.print("Total Deaths: ");
      Serial.println(TotalDeaths);

      Serial.print("Total Deaths Today: ");
      Serial.println(TotalDeathsToday);

      display.setCursor(0, 20);
      display.print(F("T Recov: "));
      display.println(TotalRecovered);

      Serial.print("Total Recovered: ");
      Serial.println(TotalRecovered);

      Serial.print("Total Territories: ");
      Serial.println(TotalTerritories);

      display.setCursor(0, 30);
      display.print(F("U T: "));
      display.println(buffUpdateMS);

      display.setCursor(0, 40);
      display.print(F("C T: "));
      display.println(buffChangedMS);

      display.display();

    }

    http.end();   //Close connection

  }

  delay(60000);    //Send a request every 60 seconds

}

```

If I run that now I get this JSON string:

{"TotalCases":4036128,"TotalCasesToday":26837,"TotalDeaths":276825,"TotalDeathsToday":849,"TotalRecovered":1400460,"TotalTerritories":214,"CurrentUpdatedMS":1589027095790,"CurrentChangedMS":1589026765665}

CurrentUpdateMS = 1589027095790 which is Sat May 09 2020 13:24:55, granted there may be an hour difference with BST.

Instead I am getting:

Sat May 9 13:23:32 2020

Also appears to stay the same after refreshes which I have set to 60 seconds.

I tried the Time.h library with same results.

Thankful for any input or suggestions.

# Answer
> 1 votes
It's hard to know what is wrong with your code... because you are not showing it in the question! Here is a basic test I tried on my Uno:

```
#include <time.h>

const uint64_t ms = 1588312648603;

void setup() {
    time_t t = ms/1000 - UNIX_OFFSET;
    Serial.begin(9600);
    Serial.println(ctime(&t));
}

void loop(){}

```

It's output is:

```
Fri May 01 05:57:28 2020

```

Note that this \<time.h\> comes from the avr-libc. It uses an epoch different from the Unix epoch, hence the `UNIX_OFFSET` correction.

**Edit**: I tried replacing avr-libc's `<time.h>` by Adafruit RTClib (declaring `DateTime t(ms/1000);`) and Paul Stoffregen’s Time library (with `time_t t = ms/1000;`). In all cases I get the same time displayed.

---
Tags: esp8266, time
---


# Question
Title: Serial communication arduino mega and D1 Wemos Mini
Can anyone help me connecting arduino mega to D1 Wemos Mini serially? Please let me know most efficient and easy steps to setup a communication.

Using that following tutorial:

https://engineeringprojectshub.com/serial-communication-between-nodemcu-and-arduino/amp/

Following is the circuit diagram: https://i.stack.imgur.com/oOKwL.png

# Answer
> 2 votes
Apart from ensuring you're wiring TX -\> RX and connecting all grounds, you can use SerialTransfer.h to automatically packetize and parse your data for inter-Arduino communication without the headace. The library is installable through the Arduino IDE and includes many examples.

Here are the library's features:

> This library:
>
> * can be downloaded via the Arduino IDE's Libraries Manager (search "SerialTransfer.h")
> * works with "software-serial" libraries
> * is non blocking
> * uses packet delimiters
> * uses consistent overhead byte stuffing
> * uses CRC-8 (Polynomial 0x9B with lookup table)
> * allows the use of dynamically sized packets (packets can have payload lengths anywhere from 1 to 254 bytes)
> * can transfer bytes, ints, floats, and even structs!!

Example TX Arduino Sketch:

```
#include "SerialTransfer.h"

SerialTransfer myTransfer;

void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
  myTransfer.begin(Serial1);
}

void loop()
{
  char buff[] = "hi";

  myTransfer.txObj(buff, sizeof(buff));
  myTransfer.sendData(sizeof(buff));
  delay(100);
}

```

Example RX Arduino Sketch:

```
#include "SerialTransfer.h"

SerialTransfer myTransfer;

void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
  myTransfer.begin(Serial1);
}

void loop()
{
  if(myTransfer.available())
  {
    char buff[40];

    myTransfer.rxObj(buff, sizeof(buff));

    Serial.println("New Data: ");
    Serial.write(buff, sizeof(buff));
    Serial.println();
  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");

    if(myTransfer.status == -1)
      Serial.println(F("CRC_ERROR"));
    else if(myTransfer.status == -2)
      Serial.println(F("PAYLOAD_ERROR"));
    else if(myTransfer.status == -3)
      Serial.println(F("STOP_BYTE_ERROR"));
  }
}

```

---
Tags: esp8266, arduino-mega, softwareserial
---


# Question
Title: Can a video game potentially detect arduino leonardo?
If I automated an action in a video game through arduino leonardo, can it be detected? Things like autohotkey can be easily detected, however i would expect an arduino would be far more difficult. How easy/difficult would it be detect?

# Answer
> 0 votes
Nigh on impossible. True the game could look to see if there is a specific VID/PID combination visible to the computer, but that is probably not going to happen (and anyway you can change it). As far as the game is concerned, input from a keyboard is input from a keyboard, whether that keyboard has buttons or a piece of code it really can't tell.

# Answer
> 1 votes
Yes.

First you'll need to define how you plan to inject the new input signal, into the data "packets" as a spoof of controller signals, or just jumping the switches?

In the context of any modern gaming console, it could be detected. Easily. Consoles and controllers use any number of proprietary protocols which sync.commands to improve response and reduce controller lag. If you're just jumping the switches, then no, you could simulate hadouken and probably get away with it just fine.

If you're referencing PC gaming, then that would be hard if not impossible with the variance of input control available. The best deterrent would be the security of the game software itself and the genre of the gaming. Some games actively encourage Hotkeys.

---
Tags: arduino-leonardo, keyboard
---


title: Arduino 5V pump digital pin

text:
# Question
Title: Arduino 5V pump digital pin
I am trying to control a 5V pump with arduino and ultrasonic sensor however i can't make it work with the pump connected to a pin.

I saw on the forum that you need transistor or relay but i don't understand why ?

Thanks !

# Answer
> 2 votes
Probably because the pump will use more current (mA) than a GPIO pin of the Arduino can deliver.

A GPIO pin on the Arduino can deliver 20 mA, or 40 mA max (but not advised for longer time).

Therefore, a separate power supplyis used, where the base pin of a transistor is connected to a GPIO pin (with a resistor) to 'switch' the transistor on and off. The transistor base can be very low current (way within a GPIO's current range), which result in a much bigger current from the collector (connected to the power supply) to the emitter (connected to GND). The pump is somewhere between the external power supply and GND).

If you search for 'transistor as a switch' you will find many examples.

You also can use a relay if you don't need to switch it on often. Relay's are typically used for net-powered devices (110+ volts) and/or high current. See also Duncan's comments for additional notes regarding relays.

# Answer
> 1 votes
@michel-keijzers has pointed you in the right direction. Depending upon the power requirements for your pump, you might consider looking specifically at logic-level power MOSFETs as the type of transistor in your circuit.

You might also investigate the use of a pull-up resistor to fully turn on a MOSFET.

---
Tags: relay, transistor, mosfet
---


title: motor controll holding ir remote button

text:
# Question
Title: motor controll holding ir remote button
im controlling some small dc motors using arduino uno and tle94112el shield. currently, i can independently controll motors by pressing remote's buttons, but i wanna keep one motor rotating by holding a button. for example, by holding "unu" button, i wanna power the motor with 50% duty cycle, as i currently do by just pressing "unu". thank you!

```
#include <TLE94112.h>
#include <Tle94112Motor.h>
#include <IRremote.h>

#define unu 0x1
#define patru 0x4
#define sapte 0x7

int RECV_PIN = 2;

// Tle94112 Object
Tle94112 controller = Tle94112();

// Tle94112Motor Objects
Tle94112Motor motor1(controller);
Tle94112Motor motor2(controller);
Tle94112Motor motor3(controller);

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  // Enable MotorController Tle94112
  // Note: Required to be done before starting to configure the motor

   irrecv.enableIRIn();
  controller.begin();

   // Connect motor1 to HB1 and HB3
  motor1.connect(motor1.HIGHSIDE, controller.TLE_HB1);
  motor1.connect(motor1.LOWSIDE, controller.TLE_HB2);

  // Drive HB1 with signal from PWM1
  // Note: This allows to control the speed of the motor

  motor1.setPwm(motor1.HIGHSIDE, controller.TLE_PWM2);

  // Set PWM Frequency, default is 80 Hz
  motor1.setPwmFreq(motor1.HIGHSIDE, controller.TLE_FREQ200HZ);

  motor1.begin();
}

void loop()
{
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value

    if (results.value == unu)
    {
      motor1.start(127);
    }

    if (results.value == patru)
    {
      motor1.start(255);
    }

    if (results.value == sapte)
    {
      motor1.start(0);
    }
  }

}

```

---

thanks for replying. i followed your instructures. when i hold the button, my remote sends continuously the same code it sends for a single press too. so in the brackets of second "if", i used the same condition that i used in first "if". following your instructions, when i prees the button, motor starts, even if i release or keep holding the button, the motor keeps rotating, but when i press the same button second time, the motor stops. so instead of "timestamp = millis()", i used "timestamp \< millis()", so in this situation, the motor was rotating as long as i kept the button pressed. now the problem is that the motor is powered with pulses, aprox. 2 impulses per second, it doesnt rotate smoothly. i tryed incresing and decreasing TIMEOUT with no effects. i also used all the pwm frequencies (80, 100, 200 hz) that the shield provides, and different duty cycles, also with no effects. but when i add 2 more motors, to controll them in the same way, each with it's own button, the pulses period was even bigger, with aprox one impuls on second. do you have any ideea about this? sorry, but its my first arduino project, i also have no experience on engineering forums. thaks for your time.

here is the code im using now:

```
#include <TLE94112.h>
#include <Tle94112Motor.h>
#include <IRremote.h>

#define unu 0x1

unsigned long timestamp = 0;
#define TIMEOUT   200

int RECV_PIN = 2;

// Tle94112 Object
Tle94112 controller = Tle94112();

// Tle94112Motor Objects
Tle94112Motor motor1(controller);

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  // Enable MotorController Tle94112
  // Note: Required to be done before starting to configure the motor

   irrecv.enableIRIn();
  controller.begin();

   // Connect motor1 to HB1 and HB3
  motor1.connect(motor1.HIGHSIDE, controller.TLE_HB1);
  motor1.connect(motor1.LOWSIDE, controller.TLE_HB2);

  // Drive HB1 with signal from PWM1
  // Note: This allows to control the speed of the motor

  motor1.setPwm(motor1.HIGHSIDE, controller.TLE_PWM2);

  // Set PWM Frequency, default is 80 Hz
  motor1.setPwmFreq(motor1.HIGHSIDE, controller.TLE_FREQ200HZ);

  motor1.begin();
}

void loop()
{
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value

    if (results.value == unu)
    {
      motor1.start(127);
      timestamp < millis();

    }

    if(results.value == unu){
      timestamp < millis();
    }

    if(millis() - timestamp > TIMEOUT){
      motor1.start(0);
    }
  }
}

```

# Answer
As I understood you want the motor to run only while you are pressing the button, stopping as you release the button. IR remote controls normally don't send a "release" signal. But they often send a "repeat" signal in a defined frequency. The value of this signal depends on the remote, that you use. A quick search showed this forum thread, where the value is `0xFFFFFFFF`.

So to check, if the button is still pressed, you need to regularly check, if the repeat code was received. When receiving the `unu` signal, turn on the motor and start a timeout counter. Every time you receive the repeat signal, you reset the timeout counter. If the timeout hits (meaning, that no repeat signal was received anymore), stop the motor.

The timeout counter is best done with the `millis()` function, which returns the number of milliseconds since startup. Refer to the `BlinkWithoutDelay` example, that comes with the Arduino IDE. Basically you save the time in a variable, when the `unu` code is received (the receive if statement is pseudo code). You reset the timestamp in the same way for every repeat code. Then you check, if the different between the current time (returned by `millis()` and the timestamp is over the timeout value (here 200ms). If yes, turn the motor off.

```
unsigned long timestamp = 0;
#define TIMEOUT   200

void loop(){
    if(unu was received){
        // turn on motor here
        timestamp = millis(); //take timestamp
    }
    if(repeat was received){
        timestamp = millis();
    }

    if(millis() - timestamp > TIMEOUT){
        // turn off motor here
    }
}

```

---

In your new version you replaces the `=` with a `<` to make it work. That is wrong. The lines, where you did it, will just do nothing then. Instead the problem lies at a different place:

The `millis()` if statement

```
if(millis() - timestamp > TIMEOUT)

```

has to be placed directly in `void loop()`, outside of the receive if statement. In your current version the timeout will only take effect, when something was received, which was not `unu`. But you want it to take effect also when nothing is received. In that case the receive if statement will not execute. So just move the `millis()` if statement outside of that receive if statement:

```
#include <TLE94112.h>
#include <Tle94112Motor.h>
#include <IRremote.h>

#define unu 0x1

unsigned long timestamp = 0;
#define TIMEOUT   700

int RECV_PIN = 2;

// Tle94112 Object
Tle94112 controller = Tle94112();

// Tle94112Motor Objects
Tle94112Motor motor1(controller);

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  // Enable MotorController Tle94112
  // Note: Required to be done before starting to configure the motor

   irrecv.enableIRIn();
  controller.begin();

   // Connect motor1 to HB1 and HB3
  motor1.connect(motor1.HIGHSIDE, controller.TLE_HB1);
  motor1.connect(motor1.LOWSIDE, controller.TLE_HB2);

  // Drive HB1 with signal from PWM1
  // Note: This allows to control the speed of the motor

  motor1.setPwm(motor1.HIGHSIDE, controller.TLE_PWM2);

  // Set PWM Frequency, default is 80 Hz
  motor1.setPwmFreq(motor1.HIGHSIDE, controller.TLE_FREQ200HZ);

  motor1.begin();
}

void loop()
{
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value

    if (results.value == unu)
    {
      motor1.start(127);
      timestamp < millis();

    }

    if(results.value == unu){
      timestamp < millis();
    }
  }

  if(millis() - timestamp > TIMEOUT){
    motor1.start(0);
  }
}

```

That way the timeout will be checked at every `loop()` iteration. As you described, that you get the code about 2 times per second, I increased the timeout value here to 700ms, which then should be enough to not let the motor stop between the receiving of the `unu` command.

---

Btw: To stop the motor you are using `motor.start(0);`. While it works perfectly, you might want to write your code more speaking. The used library internally just calls it's `motor.coast();` function, when the parameter is zero. So to make it more obvious in your code, what you are doing there, you could replace `motor.start(0);` by `motor.coast()`. That can help others to understand your code better and also yourself, when you are revising the code yourself after some time, when you may have forgotten, what you thought at that time about the code. It is always better to write code, that speaks by itself about what it is doing.
> 1 votes

---
Tags: ir, remote-control
---


# Question
Title: Arduino Ethernet Shield 2 stuck on EthernetServer::begin()
I am currently trying to get the Ethernet Shield working on my Mega. I was trying to run the Webserver example but the program seems to stuck at one point, so I tried to start from scratch.

This is my test code:

```
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = {
  0x90, 0xA2, 0xDA, 0x0F, 0xF6, 0x3D
};
byte subnet[] = { 255,0,0,0 };
byte gateway[] = { 2,0,0,1 };
IPAddress ip(2, 0, 0, 1);

EthernetServer server(80);

void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac, ip, gateway, subnet);
  Serial.println("Ethernet started");
  server.begin();
  Serial.println("Server started");
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("Loop");
}

```

The output I get from the serial console is:

```
Etrted
Ethernet started

```

So I think the program gets stuck inside the EthernetServer::begin() function. I am aware that there are earlier versions of ethernet shields which are not compatible to the mega, but the vendor of my shield says it is.

Also I don't understand, why it outputs the first line.

Thanks for your hints!

# Answer
> 0 votes
Just to get this answered (see comments): It was a weird "bug" in my case. After days of research I found people with the same issue and in their cases it helped to cut all of the pin headers but the ICSP header by 2mm so the ICSP header had better contact. I tried it on my shield and it worked.

# Answer
> 3 votes
You must use these libraries:

```
#include <Ethernet.h>  -->  #include <Ethernet2.h>
#include <EthernetUdp.h>  -->  #include <EthernetUdp2.h>

```

More info at this link Arduino Ethernet Shield2

# Answer
> 0 votes
```
// fill in your Domain Name Server address here:
IPAddress myDns(192,168,1,1);

// initialize the library instance:
EthernetClient client;

char server[] = "www.arduino.cc";

unsigned long lastConnectionTime = 0;
// last time you connected to the server, in milliseconds
boolean lastConnected = false;
// state of the connection last time through the main loop
const unsigned long postingInterval = 14*1000;
// delay between updates, in milliseconds

void setup() {
  pinMode (pin, OUTPUT);
  digitalWrite (pin, LOW);

  // start serial port:
  Serial.begin(9600);
  // give the ethernet module time to boot up:
  delay(1000);
  // start the Ethernet connection using a fixed IP address and DNS server:
  Ethernet.begin(mac, ip, myDns);
  // print the Ethernet board/shield's IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  if (client.available()) {
    Serial.println ("1"); delay(500);
    char c = client.read();
    Serial.print(c);
    } else {Serial.println ("11");delay (500);}
  // if there's no net connection, but there was one last time
  // through the loop, then stop the client:
  if (!client.connected() && lastConnected) {
    Serial.println(2); delay(500);
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  } else {Serial.println ("22");delay (500);}

  // if you're not connected, and ten seconds have passed since
  // your last connection, then connect again and send data:
  if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
    Serial.println(3); delay(500);
    httpRequest();
    Serial.println ("4");delay (100);
  } else {Serial.println ("33");delay (500);}
  // store the state of the connection for next time through
  // the loop:
  lastConnected = client.connected();
  Serial.println ("end loop");
}

// this method makes a HTTP connection to the server:
void httpRequest() {
  // if there's a successful connection:
  Serial.println ("httpRequest"); delay(500);
  if (client.connect(server, 80)) {
     Serial.println ("H1"); delay(500);
    Serial.println("connecting...");
    // send the HTTP PUT request:
    client.println("GET /latest.txt HTTP/1.1");
    client.println("Host: www.arduino.cc");
    client.println("User-Agent: arduino-ethernet");
    client.println("Connection: close");
    client.println();

    // note the time that the connection was made:
    lastConnectionTime = millis();
  } else {
    Serial.println ("H11"); delay(500);
    // if you couldn't make a connection:
    Serial.println("connection failed");
    Serial.println("disconnecting.");
    client.stop();
  }
}

```

I inserted debug lines. all I get are the faileure "if" comments. after 15 seconds, I get debug #3 and then "HTTP Request" then nothing but crickets....

---
Tags: arduino-mega, ethernet
---


# Question
Title: Load Adafruit GFX bitmap fonts on desktop for pixel-level design
I am designing UI for 160x128 ST7735-based TFT display which will be displayed using Adafruit's GFX library (and the driver in `Adafruit_ST7735.h`). I am using the default bitmap font (custom fonts don't provide the white-out functionality, causing flicker) and would like to load it in some desktop pixel editor (like Gimp or some pixel-art editor) so that I can work the design out on desktop.

There are many posts about converting regular (TFT, OTF) fonts to the c-style array, I need to do the opposite. If possible, including the scaled variants, so that I have 1:1 corespondence :)

Any tips on this?

# Answer
> 0 votes
As explained here and here the font format in the GFX-library is GFXglyph, you can use the free tool from the second link adafonteditor v1.0.3 on the desktop.
**EDIT**
Ok so its actually decompile the gfx header file to something on the desktop. Take a look at the Adafruit GFX Font Customiser Source can be used as basis for own projects or compiled to the designated OS.

---
Tags: adafruit
---