text:
Inconsistant compilation error
It is s a bit complicated to ask such question, but what may be the reason that one time  compilation passes and other fails without any changes in code? surely debugging this way is very hard (one time commenting out one part of code seems to stop this problem and later it returns even if commenting out was canceled).
I suspect it has to do with some changes in code regarding some ArduinoJson functionality
Sketch was was tested on 2 different platforms, Linux and Mac, and error occurs on both.
What troubles me is compilation inconsistentancy rather than some bugs in my code.
Error message:
/home/guy/snap/arduino/70/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/bin/../lib/gcc/xtensa-lx106-elf/10.3.0/../../../../xtensa-lx106-elf/bin/ld: sketch/inFlash_Parameters.ino.cpp.o: in function `_Z17updateTopicsFlashRN18ArduinoJson6171_9112JsonDocumentE':
/home/guy/Documents/Dropbox/Arduino/libraries/myIOT2/examples/inFlash_Parameters/myIOT_settings.h:46: undefined reference to `_ZN6myIOT223extract_JSON_from_flashEPcRN18ArduinoJson6171_9112JsonDocumentE'
/home/guy/snap/arduino/70/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/bin/../lib/gcc/xtensa-lx106-elf/10.3.0/../../../../xtensa-lx106-elf/bin/ld: /home/guy/Documents/Dropbox/Arduino/libraries/myIOT2/examples/inFlash_Parameters/myIOT_settings.h:44: undefined reference to `_ZN6myIOT228update_vars_flash_parametersERN18ArduinoJson6171_9112JsonDocumentE'
/home/guy/snap/arduino/70/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/bin/../lib/gcc/xtensa-lx106-elf/10.3.0/../../../../xtensa-lx106-elf/bin/ld: sketch/inFlash_Parameters.ino.cpp.o: in function `_ZN18ArduinoJson6171_9110MemoryPoolC4EPcj':
/home/guy/Documents/Dropbox/Arduino/libraries/myIOT2/examples/inFlash_Parameters/myIOT_settings.h:52: undefined reference to `_ZN6myIOT223extract_JSON_from_flashEPcRN18ArduinoJson6171_9112JsonDocumentE'
/home/guy/snap/arduino/70/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/bin/../lib/gcc/xtensa-lx106-elf/10.3.0/../../../../xtensa-lx106-elf/bin/ld: sketch/inFlash_Parameters.ino.cpp.o: in function `_Z22readParameters_inFlashv':
/home/guy/Documents/Dropbox/Arduino/libraries/myIOT2/examples/inFlash_Parameters/myIOT_settings.h:52: undefined reference to `_ZN6myIOT228update_vars_flash_parametersERN18ArduinoJson6171_9112JsonDocumentE'
/home/guy/snap/arduino/70/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/bin/../lib/gcc/xtensa-lx106-elf/10.3.0/../../../../xtensa-lx106-elf/bin/ld: /home/guy/Documents/Dropbox/Arduino/libraries/myIOT2/examples/inFlash_Parameters/myIOT_settings.h:57: undefined reference to `_ZN6myIOT223extract_JSON_from_flashEPcRN18ArduinoJson6171_9112JsonDocumentE'
/home/guy/snap/arduino/70/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/3.0.4-gcc10.3-1757bed/bin/../lib/gcc/xtensa-lx106-elf/10.3.0/../../../../xtensa-lx106-elf/bin/ld: /home/guy/Documents/Dropbox/Arduino/libraries/myIOT2/examples/inFlash_Parameters/myIOT_settings.h:59: undefined reference to `_ZN6myIOT223extract_JSON_from_flashEPcRN18ArduinoJson6171_9112JsonDocumentE'
collect2: error: ld returned 1 exit status
Multiple libraries were found for "WiFiUdp.h"
 Used: /home/guy/snap/arduino/70/.arduino15/packages/esp8266/hardware/esp8266/3.0.2/libraries/ESP8266WiFi
 Not used: /home/guy/Documents/Dropbox/Arduino/libraries/arduino_648747
 Not used: /home/guy/Documents/Dropbox/Arduino/libraries/WiFiNINA
 Not used: /snap/arduino/70/libraries/WiFi
Multiple libraries were found for "ArduinoJson.h"
 Used: /home/guy/Documents/Dropbox/Arduino/libraries/arduino_215091
 Not used: /home/guy/Documents/Dropbox/Arduino/libraries/arduino_892158
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

Sharing function that are mentioned in error to make the picture clearer:
void updateTopicsFlash(JsonDocument &DOC)
{
    for (uint8_t i = 0; i < 3; i++)
    {
        sprintf(topics_gen_pub[i], DOC["pub_gen_topics"][i]);
    }
    for (uint8_t i = 0; i < 3; i++)
    {
        sprintf(topics_pub[i], DOC["pub_topics"][i]);
    }
    for (uint8_t i = 0; i < 2; i++)
    {
        sprintf(topics_sub[i], DOC["sub_topics"][i]);
    }
}

void readParameters_inFlash()
{
    StaticJsonDocument<1250> DOC;

    iot.extract_JSON_from_flash(parameterFiles[0], DOC);
    iot.update_vars_flash_parameters(DOC);
    DOC.clear();

    iot.extract_JSON_from_flash(parameterFiles[1], DOC);
    updateTopicsFlash(DOC);
    DOC.clear();

    iot.extract_JSON_from_flash(parameterFiles[2], DOC);
    DOC.clear();
}

calling 2 functions from lib:
bool myIOT2::extract_JSON_from_flash(char *filename, JsonDocument &DOC)
{
    File readFile = LITFS.open(filename, "r");
    DeserializationError error = deserializeJson(DOC, readFile);
    readFile.close();

    if (error)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}
void myIOT2::update_vars_flash_parameters(JsonDocument &DOC)
{
    useWDT = DOC["useWDT"];
    useOTA = DOC["useOTA"];
    useSerial = DOC["useSerial"];
    useFlashP = DOC["useFlashP"];
    useDebug = DOC["useDebugLog"];
    debug_level = DOC["debug_level"];
    useResetKeeper = DOC["useResetKeeper"];
    useNetworkReset = DOC["useNetworkReset"];
    noNetwork_reset = DOC["noNetwork_reset"];
    useBootClockLog = DOC["useBootClockLog"];
    ignore_boot_msg = DOC["ignore_boot_msg"];
}

Copy the files out of Dropbox and try again.

@romkey Can you explain why?

I think @romkey is observing that in the error messages you posted each of the references to files at Dropbox locations produced an Undefined reference error. It seems logical to move those files locally and see if the error behavior becomes more consistent.

@RowanP I was thinking about this factor after @romkey mentioned it. Still, .ino file, and .h file are local, and haven't changed at that point of re-compile ( I'll surely try what romkey suggested)

You're saying that you don't get the same results when you compile twice. That doesn't happen and you're confused by it. A large chunk of your files are resident on a file synchronization service, which can change your files without you being aware of what it's doing. If you want to debug this that's the obvious thing to take out of the equation.

Not related to the problem you are facing, but I looks at the data that you are retrieving from flash, instead of using json, it would be much more easier to deal with and much more efficient to store by using a struct.

The OP question looks very similar to this bug report https://github.com/arduino/Arduino/issues/2574


text:
Frequency measuring using Arduino (AC analog input)
What I aim to do:
To measure the frequency of an AC analog signal generated by an electrodynamic shaker, which has a peak voltage of 10V-- using an Arduino Uno.
What I have tried:
Tried using a circuit similar to an optocoupler (using a 2N2222) transistor to take pulse input, using the pulsein() function. However the duration is always returning as 0.
My questions:

Is this method an acceptable way of measuring frequency?
What could I be doing wrong such that the time duration is always returning 0?
Is there an easier way of carrying out this work?

Will put up the code if asked for. However it is basically just defining a few variables (for pins, duration etc), and then using the pulsein function.

Please provide a schematics or wiring, how you have the signal connected to the Arduino. What form does the signal have? Are you doing some preprocessing, or do you simply rely on the Schmitt Trigger inside the digital input of the Arduino?

I have added the circuit diagram. I'm not using a Schmitt trigger since my professor has explained to me that the circuit I am using will convert the AC signal  to pulses, which can be read by the digital input pins of the Arduino. However, I do admit I am not an electronics engineer, so my knowledge about this is quite limited.

Try adding a resistor between base and emitter of the transistor to pull the base to ground, when the phototransistor of the optocoupler is not conducting. That should keep the transistor base from floating. Though it is only a guess, that this is a problem. Can you observe the signal and the output of the circuit with an oscilloscope?

The output, as shown, goes to the Arduino digital pin. I looked at the input signal to ensure it is indeed sinusoidal. However I have not looked at the output. I will do so. Thank you for your input!

Why the transistor? The optocoupler already includes a (photo-)transistor, so why add another one? 2. pulseIn() measures the length of a pulse, i.e. the time between a rising edge and the following falling edge (or vice-versa). For measuring a frequency, you need the time between two consecutive rising (or falling) edges. 3. What is the range of frequencies you want to measure? What kind of accuracy do you need? There are many methods to measure a frequency, and the “right” one for you depends on your requirements.

This project includes a frequency counter.
https://www.instructables.com/id/Oscilloscope-in-a-Matchbox-Arduino/
From the project page:
This oscilloscope costs the price of an Arduino Nano (£2 and a display (£3) plus a few pence for resistors, etc. It's specification is:

max 1M samples/second, min 1000sps
8-bits per sample
DC 0-5V; AC +/- 550mV, AC +/- 117mV, AC +/- 25mV
USB "PC scope" or built-in display
could be battery-powered
optional logic display
optional frequency meter
optional voltmeter
optional signal generator

My comment: I build it, it's a nice little project and the author is an expert programmer.

Answers should be more selfcontaining. A link-only answer would get completely useless, when the link dies eventually. Please include the key points directly in the answer text.

@chrisl: thanks for the info, done

Is this method an acceptable way of measuring frequency?

Nope, not at all.

What could I be doing wrong such that the time duration is always returning 0?

You are misusing pulsein(), it doesn't work like that; look up the documentation for it!

Is there an easier way of carrying out this work?

Yes; there are many ways, you can research many of them. One thing you can do is make a peak detector, either in hardware or software, and then design a way to get a counts/time, which should correlate to the frequency!

source: Stack Exchange

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

sort: votes


text:
Soft debouncing from an interrupt during stand-by
My current setup has the arduino in 'stand-by' power saving mode, therefore i am unable to use any means of a traditional soft debouncer, such as Bounce2, as far as I know.
I went ahead and attached the buttons to pin change interrupts, since I have one button on each bank, i.e. pin 7 and pin 11.
The technique I'm using doesn't seem to be behaving since the routines are being fired too regularly (inconsistently), and at the rising edge too.
I have the pins set to use their internal pull-ups.
Using the PCI library:
void pciSetup(byte pin)
{
  *digitalPinToPCMSK(pin) |= bit (digitalPinToPCMSKbit(pin));  // enable pin
  PCIFR  |= bit (digitalPinToPCICRbit(pin)); // clear any outstanding interrupt
  PCICR  |= bit (digitalPinToPCICRbit(pin)); // enable interrupt for the

pciSetup(POWER_SWITCH);
pciSetup(SELECTOR_BTN);

// check if IR IN or Power switch
ISR (PCINT0_vect) // handle pin change interrupt for D8 to D13 here
{

  if (digitalRead(POWER_SWITCH) == LOW)
  {
    noInterrupts();
    unsigned long last_millis = millis();
    while (millis() - last_millis >= 500);
    ir_power_pressed = true;
  }
  interrupts();
}

ISR (PCINT2_vect) // handle pin change interrupt for D0 to D7
  noInterrupts();
  unsigned long last_millis = millis();
  while (millis() - last_millis >= 500);
  ir_selector_pressed = true;
  interrupts();
}

Am I doing something silly?
Update 1
As suggested in the comments, i've adjusted the code, but it still triggers on the rising edge, and a few times rapidly at the falling edge.
ISR (PCINT2_vect) // handle pin change interrupt for D0 to D7 here
{
  if (digitalRead(SELECTOR_BTN) == LOW)
  {
    noInterrupts();
    static unsigned long last_millis = millis();
    if (millis() - last_millis >= 500)
    {
      ir_selector_pressed = true;
      interrupts();
    }
  }
}

Hardware debounce with capacitor and resistor?

Make last_millis static, and replace the while loop with an if statement.

@Mike I would do that, but i've put a new MCU in a pre-existing PCB so there's not much space, it'll be my last resort.

@tttapa I did so, but it's still triggering on the rising edge, and firing very fast a few times at the falling edge.
Please see the update for the updated code.

You don't update last_millis.
Also, you don't know whether SELECTOR_BTN went from HIGH to LOW or whether another pin fired the interrupt while SELECTOR_BTN was low. Remember the previous state to solve this.
const unsigned long debounceTime = 50;
volatile bool ir_selector_pressed = false;

ISR (PCINT2_vect) { // handle pin change interrupt for D0 to D7 here
  static unsigned long previousStateChangeMillis = 0;
  static bool previousPinState = HIGH;

  bool pinState = digitalRead(SELECTOR_BTN);
  if (pinState != previousPinState) { // ignore pin changes of pins other than SELECTOR_BTN
    if (pinState == LOW) { // only falling events
      if ((millis() - previousStateChangeMillis) > debounceTime) { // debounce
        ir_selector_pressed = true;
      }
    }
    previousPinState = pinState;
    previousStateChangeMillis = millis();
  }
}

Thank you, this works very well. Is there a reason why you're not deactivating interrupts during the ISR body?

When an interrupt service routine (ISR) is called, interrupts are automatically disabled.  Interrupts are automatically enabled when returning from an ISR.  It is not necessary to explicitly enable nor disable interrupts inside of an ISR.  The processor does these two things for you. Source

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


text:
Fast wired communication protocols
I have an esp32 connected to an FPGA about 2 cm on a PCB. I am trying to send a constant data stream to the FPGA at a throughput of around 1.5 MB/s.
This is too fast for UART, I've been considering SPI but I don't really know how I can implement it in the FPGA.
Are there any other fast data communication protocols over wires available to me, or even a parallel protocol ?

An SPI receiver-only port is little more than a shift register.

@EdgarBonet I will give SPI a go then, sounds like the most obvious choice

I believe there are wider SPI bus implementations.  Like 2 data lines or maybe even more.  Maybe that will give you more through put.  But do you need full-duplex?  I2C is half-duplex and uses fewer pins. But timing is more critical.  There is also an audio serial bus protocol.  Maybe you should look into that one.

@st2000 thanks, I am only using a half duplex set up, I very briefly looked at I2S but it seemed a little too slow, I may well have overlooked something. I think SPI may be the one.

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


text:
Hacking a Chinese Audio Selector Board: IRLib2 with Low Power Sleep Issue
I have an issue getting an arduino based hacked-board to sleep whilst performing ir remote commands properly.
What am i hacking?
Exactly this:
tl;dr it's a 4 in 1 out audio selector with motorised volume pot controllable by an IR remote. But it's got a lot of issues so i've enjoyed hacking it. I will release full details maybe with a re-done PCB layout should people wish to grab a board / diy kit, but at the moment it looks like this:

Why am i hacking it?
As is, it's closed hardware and closed software, the MCU itself is an STC15W408AS which prides itself on not being able to have its flash memory read, and believe me it does it's job well; I've clearly removed it and pulled out the SOP20 footprint to another pcb that can talk to either the original IC, or an arduino nano. the volume pot as well is too slow and requires tapping to change, the relays are not latching so consume a lot of power, the whole unit consumes too much power, and i've more of less changed the majority of the components and layout.
So what's the issue?
I got to a point where i've got quite a nice setup in terms of design, it's more of less exactly how i want it and how an audio component should perform, transparently. This is why i'm now optimising the code, with a strong emphasis on lowering the idle power consumption, given it's an always on device.
The original code can be viewed here:
I've already got it down from 150mA to ~65mA by lowing the clock to 8MHz, removing the regulator, LEDs and everything else that's unnecessary, and have disabled a few modules on the ATmega328 itself, as seen on line 88.
The aim is to have it sleep when it's not being used, but i had a few set-backs since with the intention vs implementation, when it came to the ir demodulator.
A post by Nick Gammon discussed how to put the board to sleep when it's been inactive for more than two seconds whilst using IRLib1.
So i went along and ported that code to IRLib2 shown here, then retrofitted it with my original code, essentially putting the bulk of my IR response code in the 'storeCode' function (shown in the forum post, of course i refactored to more appropriate names).
The code itself works well, but it 'soft-bricks' at rather random intervals (system freezes until manual reset), usually after a few button presses, and almost at every repeat code, [The original code behaves as intended] (i do use repeat codes to allow the user to hold a volume up/down button to continuously change it, i haven't yet ported that functionality to the new sleeping code since it sleeps after 2 seconds of holding, but have begun playing with an idea seen on line 173.
I can see the current draw with the new code is low, at about 10mA for the entire board which is more than ten times lower than before, so i'll be really happy if anyone can point me in the right direction.

Questions on SE sites need to be far more concise - try to shrink this to a piece of a code that will fit in the question itself, and still demonstrate the problem.  That's not only key to making the issue accessible for others to help, there's a good chance that the process of distilling it will lead you to discovery the issue yourself.

@ChrisStratton Thank you for your feedback, I will try to alter the code so it's just showing one example of the fault, then maybe show a before and after. The only issue is i don't know where in the code (or hardware) the fault is occuring, i will try to focus on the code that's new - that being the sleep code.

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


text:
How should you predict the battery size required for a project?
I am using an Arduino nano along with an ESP8266.  The nano is connected to an OLED display and a keypad. The ESP8266 uploads the data entered from the keypad onto a server. I wish to make the device portable; i.e. add a battery to it so that it can last for at least 8 hours.
How can I calculate the rating for the LiPo battery to use? I understand that it is very important to know the current rating of the devices in use.
How can I make an approximate guess?

You don’t guess, you measure. Use a multimeter to get a rough indication. Make sure you measure different states of your program. For example, sending data uses more power

if you want to save power, get rid of the nano; the esp can run a screen and keypad directly...

I do not possess some of the components with me presently so how can I ?

Yes, you need to know the average current draw over the period of an hour (or over a period that you then extrapolate to an hour).  That is the mAh (milliamps per hour) that your circuit draws.
It can be hard to calculate the actual current, though, since it is always changing depending on what is actually happening in your system at the time.  So I would suggest picking up a cheap current monitoring USB dongle from eBay / Amazon / Wherever (one with an LCD screen that gives mAh, such as this one and use that to get the total mAh of your system over an hour.
Multiply that mAh by 8 (the number of hours you want it to run for), and that will give you the minimum mAh for your battery. And then add some more as a safety margin, since the capacity of a battery is subject to many things (like temperature, age, etc), and the rated value is only a rough guide.
For instance, if you find your circuit uses on average 387mAh, then a battery of 3600mAh should be adequate.

You should probably have them factor in how long they want the project to remain on while using battery power, instead of just multiplying by 8. I’ve had projects that only consumed 120mAh but had a 12000mAh battery because it needed to last a very long time without charging.

The "8" is how long the want it to stay on battery. " wish to make the device portable, i.e. add a battery to it so that it can last for at least 8 hours."

Your wording in the answer made it seem that 8 was an arbitrary rule-of-thumb, IMHO

Does that read better for you?

Much better. I know when I was learning omissions like that confused me.

Current consumption is measured in Amperes, battery capacity in specified in Amperes per hour.

So if a device is rated 5V/2A then does it mean that it draws 2A in one hour or 2A instantaneously?


text:
Will the pro trinket gamepad library work on an Arduino Uno?
I have an Arduino Uno and I wanted to know if the pro trinket gamepad library works on an Arduino Uno since both have same atmega328p CPU chip.

why don't you try it? ... then ask a question about any problem that you encounter

I’m not familiar with the pro trinket device (https://learn.adafruit.com/introducing-pro-trinket/pinouts?view=all) but looking at the library (https://github.com/buxit/Pro_Trinket_USB_Gamepad) readme says it is an Arduino library. I suspect it would come down to checking pins and peripherals to decide whether it will work on Uno. @jsotola’s suggestion is practical, why not try it and see? I’d put my money on your having a reasonable chance of success.

The Pro Trinket has a USB connector wired to the ATmega328P, and the
Pro_Trinket_USB_Gamepad library uses this connection to impersonate a
USB gamepad.
The Arduino Uno also has a USB connector, but it is not wired to the
ATmega328P. It is instead connected to an auxiliary chip (an ATmega16U2)
which serves exclusively as a USB-to-serial converter. Since your
sketches run on the 328P, and the 328P has no access to the USB port,
you cannot use this library on the Uno.
Well, actually you may be able to use the library if add an extra USB
connector, and link it to the 328P. See how it is done in the schematic
of the Pro Trinket 5V. Beware of the 3.6V Zener diodes:
these are needed to avoid damaging the serial port of your computer.


text:
Looking for a very simple board
I’ve worked with esp8266/esp32 boards in the past and they were great. But now I have a very simple project where both of these are way too powerful.
I want to read one analog input over USB per COM. That’s it. No wifi, no Bluetooth, no 32 bit or any of these fancy things.
It should be programmable without any hardware other than a computer though. It doesn’t need to be Arduino. All it has to do is to read the input and respond to serial communication.
But I’m absolutely overwhelmed by all these microcontrollers. Most of them are feature packed.
So I’m asking for a way to find a proper controller/board on my own. Feel free to recommend one though.

How about the Arduino Nano?

There is a non-exhaustive list of Arduino and similar boards on Wikipedia which may be of use in the comparison. https://en.wikipedia.org/wiki/List_of_Arduino_boards_and_compatible_systems?wprov=sfti1

Also there is a great article “When Less Is More - The Smallest Arduino Boards for Your Needs in 2022” by Matteo Parenti on all3dp.com with a well written comparison of small form factor arduinos and clones. https://all3dp.com/2/smallest-arduino-board/

Since you require USB, nano/micro are your way forward.
being mass produced anything smaller would actually turnout to be more expensive.
If you for those reading this message latter: If you do not need USB then you have a pro-miny (needs USB->ttl for programing)
If you are going really minimalist you can go with MSP430 chips (arduino programming available via PlatformIO).
Atmega32u4 can although run on its own without crystal, but I find Crystal free (using builtin crystal) run of MSP430 much better with timing.
Problem with MSP430 is that TI software development dedepartment is stuck in middle ages. (I am not sure if they even employ a full-time programmer) and if you are programming on arm, you might Have a problem compiling it from arm platform.

Since you seem to have some experience, seemingly these are valid options:

Obtain the smallest Arduino you can get. For example, a DigiSpark  original or clone, or a DFRobot Beetle. Use the Arduino IDE to program it.

Obtain the smallest AVR board you can get. For example, with an ATmega32u4. Download ASF, the Atmel Software Framework, learn how to use it. It provides a lot of sources for ADC and USB.

Keep in mind that sometimes "less is less".  The entire Arduino ecology is pretty cheap, so  maybe concentrate on ease-of-use instead of hardware features.  After all, if you value your time at some non-zero dollar amount, it may be that using a more 'feature-rich' (but still cheap) Arduino-ish board will be cheaper (and less frustrating) in the end.


text:
Will I need the internal pullup resistor if no button is used?
Given I have two Arduinos that are supposed to primitively communicate with each other using digital pins. On Arduino Ar1, pin D13 is to be used as an input, connected to Ar2's D2 pin.
Will I need to use the internal pullup resistor of Ar1 on pin 13, or is an outputted signal of LOW/HIGH already dragged to 0V/5V?

It's better to not think of the pullup resistor as part of the input (even though physically it is inside the chip) but instead think of it as part of the button circuitry. Thus if you're not using a button then the button circuitry doesn't exist, and that includes the pullup resistor.

If you set a pin to output mode in Arduino, it is "push-pull". This means, that any value, 0 or 1, is actively driven.
Therefore, you do not need a pull-up or pull-down resistor on the receiving input.

You need such a resistor, only if the driver does not drive the voltage actively. For example, this is the case with buttons or switches, which simply open and close a contact.
Some output modes exist like "open-drain" that only drive to GND at a value of 0, but do not drive the output pin at a value of 1. Such modes are not used if you call pinMode().


text:
How can I break the loop if it hasn't finished in 10 seconds?
Currently I am using OneButton.h library to code  my push button project.
When I press button1, it will loop for 10sec and print TRIG, and after that it will break the loop.
However, now I want to program it where when I pressed button1, it will jump to void(singleclick) function, but right now, during the 4th seconds (anytime before 10th sec) , I pressed other button, thus Arduino will break the 10sec loop and run other function.
Thus, I need help how to make sure Arduino actively read other button and when pressed, it will break the current loop/function to other related functions.
#include <OneButton.h>

OneButton button1(2, true);
OneButton button2(3, true);
OneButton button3(4, true);
OneButton button4(5, true);

int led1=12;
int led2=11;
int led3=10;
int led4=9;

int flag;

unsigned long mode;

void setup()
{

  Serial.begin(9600);
  pinMode(led1,OUTPUT);
  pinMode(led2,OUTPUT);
  pinMode(led3,OUTPUT);
  pinMode(led4,OUTPUT);

  button1.attachClick(singleclick1);
  button1.attachLongPressStop(longclick);

  button2.attachClick(singleclick2);
  button3.attachClick(singleclick3);
  button4.attachClick(singleclick4);

   digitalWrite(led1,HIGH);
   digitalWrite(led2,HIGH);
   digitalWrite(led3,HIGH);
   digitalWrite(led4,HIGH);

}

void loop()
{
  button1.tick();
  delay(20);

  button2.tick();
  delay(20);

  button3.tick();
  delay(20);

  button4.tick();
  delay(20);

  Serial.println("No button");

}

void singleclick1()
{
   mode=millis();

   flag=1;

   while(flag==1)
   {
     Serial.println("button1");
     digitalWrite(led1,HIGH);
     digitalWrite(led2,LOW);
     digitalWrite(led3,LOW);
     digitalWrite(led4,LOW);

     if(millis()-mode>5000)
     {
      Serial.println("TRIG");
      flag=0;

      button2.tick();
      delay(20);

      button3.tick();
      delay(20);

      button4.tick();
      delay(20);

      return;
     }
   }
}

void singleclick2()
{
   Serial.println("button2");
   digitalWrite(led1,LOW);
   digitalWrite(led2,HIGH);
   digitalWrite(led3,LOW);
   digitalWrite(led4,LOW);
}

You could run a timer that toggles a flag after 10 seconds. Then the loop would check that flag on each iteration.

This is just a rough, incomplete and untested code.
void singleclick1() { startTimer = true; }      // this only sets a flag

void singleclick2() { runTimer   = false;}      // this only clears a flag

void loop() {

   button1.tick();
   button2.tick();

   if startTimer {                 // this occurs once every click 1

      mode        = millis();
      runTimer    = true;
      startTimer  = false;         // run this block only once every click 1

      digitalWrite(led1, HIGH);
      digitalWrite(led2, LOW );
      digitalWrite(led3, LOW );
      digitalWrite(led4, LOW );
   }

   unsigned long currentMillis = millis();

   if (currentMillis - mode > 10000) {
      runTimer = false;                      // 10 second timer expired
   }

   if (runTimer) {

      Serial.println("TRIG");

   }
   else {
      // optional stuff to do
   }
}

Thank you so much!


text:
Use SPI and I2C in the same circuit (ATtiny85/84)
There is a previous question about this same topic here, but it does not answer my question.
I want to use a generic I2C OLED 128x64 px display and an SPI RF24 radio in the same sketch. I know that it's theoretically possible to do so as long as they're not used at the same time - my question concerns the implementation of this circuit. Can I just leave the two devices as-is without needing some kind of external apparatus to switch power to each one of them?
I know that for SPI a chip will just ignore everything when its CS pin is pulled high, and from my tests the SPI communications don't affect the SDA line of the I2C - the problem comes when I try and use the CLK and SCL line with this setup. The pullup resistor in my circuit is stopping the I2C SCL line from working. When I remove the wire (green in the breadboard schematic shown) that connects the CLK to one end of the diode the I2C starts working and the display updates, but the radio doesn't work. If I remove the pullup resistor from the circuit the I2C starts working again, but the radio doesn't work anymore. I tried switching the CLK signal with a transistor, but it doesn't look like the 2n2222 transistor I was using is fast enough to switch the CLK signal. Will I have to go with the tiny84, or is there a way to get this to work on the ATtiny85?

Do you have a AtTiny 85 of 84? They are quite different, you know. Which pins do you need to use for I2C? Which pins do you need to use for SPI?

ATtiny8X does not have specific hardware support for SPI and I2C instead there is a hardware module called USI that can be used to implement SPI and I2C. Your alternative is to use USI for one of the protocols (for instance I2C) and additional pins for software SPI.

I2C should ignore any commands that don't make sense or aren't addressed to it; you can share

Alex - I2C uses addresses rather than a CS line, so the first(?) byte of the message says who the messages is for.  Each device has two addresses, a read and a write address which is actually only different in bit7.  Don't forget you 4.7K pull-ups on the SDA and SCL lines.

@CodeGorilla ok thanks. I isolated the problem that's not allowing my setup  to work and updated my question.

In the setup shown, you have 3 pins free, yes? Although hardware i2c may not be directly possible through software, the use of the other GPIO pins can be used for either a logic circuit to switch around the pull up resistor/green wire/whatever OR you can just use software i2c which is a lot easier to do.


text:
No Battery Microcontroller Operation - (Motion, heat, induction etc)
I am using an ATtiny85 to sleep for a long period of time, collect some data, send it over radio, and go back to sleep, after disabling everything possible. The ATtiny is currently powered by a coin cell. I can get quite some time off that coin cell, but it's simply not enough, and the coin cell cannot be changed once the board is deployed. Peak current draw is around 10-15 mA.
My aim here is to find an alternative power source for my board. Some good news is that the boards are never more than one or two feet from a receiver, so rf-like power transmission may be possible. Some other options may be motion or heat (it's a wearable device). The amount of power could be pretty small, as I only need it at peak periods, so I could just charge up a supercapacitor for a while and drain it when power is needed after the Attiny wakes up for less than a second.
The ideal situation would be to have a means of power transmission or generation that provides enough current to continuously power the microcontroller without the need for sleep, but I recognize that this is probably not feasible. However, due to the limited range it might be. Another concern is radiation to the wearer.
If anyone has any experience in this kind of power transmission or generation or just any ideas I would love to hear it. Thanks!

I can get quite some time off that coin cell, but it's simply not enough - please specify numbers. You get x days off the coin cell, but you want y days? What are x and y? I have a post about a solar powered Arduino which may be relevant to you. I can elaborate in an answer (rather than just giving a link) if you think it would be useful.

I can get a few weeks depending upon usage, and I need a few months. Unfortunately, solar is out of the question for this project

a few weeks on a single coin cell is quite short. I think you should be able to get a lot more time out of it in software. e.g. disabling all unused modules; combining data, and sending it all at once; not sending data if data hasn't changed; etc. But without any specifics it's hard to say. Have you measured the standby current? How often do you collect/send data per hour? What radio are you using? Do you put the radio to sleep? What code are you using?

As soon as you use a radio, you are looking at wasting power in RF circuits. Most power is wasted in PA in RF circuits. A Li cell like CR2032 can't survive in RF transmission tanks. Some power would always be reflected (and wasted) due to impedance mismatch irrespective of your perfect RF circuit.

10mA is quite a lot for a coin cell. And of course the duration is really low.
As for wireless power transmission, I highly discourage you. Since you are using coin cell batteries I think that size is a must for you, and for wireless power you will need a really big antenna. If it is a wearable I think that the receiver is on the body too, and so much power is not a good thing.
In my opinion and according to my experience you have two possibilities:

use alkaline batteries (e.g. AAA). Use a step up driver to get 3.3V from 1.5V (since the current you need is low you can use simple charge pump regulators, so with a 10pin TSSOP integrate and three small capacitors you are done) and you will get a really long lasting circuit. Drawback: AAA batteries are a bit large, so probably you'll have to make a bigger receiver
use lithium batteries (usually I use LiPo). You will then be able to recharge the battery with any power supply (I usually use an IC which can charge LiPos with a 5V source - USB - and a couple of other components (two capacitors and a LED with its resistor).

Personally I struggled with coin cells for a long time before giving up and sticking with lipos forever.

Unfortunately I can’t charge or access the devices once deployed. I was thinking of using a cr123a as a last resort, because it’s small but still delivers 3v. I might be inclined to agree with you about coin cells - they’re more trouble than they’re worth.

Instead of that I'd still prefer a lipo one.. In the end they have similar capacities and sizes, but once a CR123A expires you have to change it, while when the LiPo does you simply recharge it.. (note: I'm not a LiPo batteries seller XD)

@frarugi87 Do you have any charge pump regulators you recommend (i.e. recommended part nr)?

Well, for my projects I used the MAX1759, which is an adjustable regulated charge pump, and the MAX1595, with fixed voltage (either 3.3V or 5V). The second one is smaller, delivers more current and requires less components, so if you want either 3.3V or 5V the second is better. I usually use these because they are regulated (and very stable), use small components (just three ceramic capacitors the 1595) and, most important, they deliver a reasonable amount of current (100mA the adjustable version, 125mA the fixed voltage one). And.. no, I'm not from Maxim ;)

This question seems to be aligned to your other question about nrf24l01+ transceiver. The charge pump is a good idea, but if this is still for the nrf24l01+ project i would not recommend it because it would cause ripples in the supplied power and RF noise which is really not something you want together with the nrf24l01+.
if the unit is to be strapped on the wrist or ankles a concept like the one in a shake/faraday flashligt might be implemented, but that would be a diy custom job. and probably require size, even though they can fit a similiar contraption into a wristwatch.
But anyway I'm not sure if you are aware, but the nrf24l01+ has a function called enhanced shockburst which is designed for very low current consumption according to the datasheet it only requires 1% or 0.12ma at normal transmitting mode! this comes at the cost of transmitting power ofcourse but your receiver is only a few feet away so that is most likely not an issue.
https://www.sparkfun.com/datasheets/Components/SMD/nRF24L01Pluss_Preliminary_Product_Specification_v1_0.pdf page 14
I'm pretty sure you already have optimised your current consumption, but one setting you might have missed is  the atTiny clockspeed which can be lowered to 1mHz instead of 8mHz this will lower the current to run the processor to 20 of the normal.
if these are not implemented already, then they might give you the needed battery life.

Thanks for the info on shockburst, I’ll look into that. The Attiny is already running at 1MHz. I didn’t know that it could transmit with such low power...

I have not had an opportunity it test it, so I don't if they are overselling it so to speak - but I'm waiting for my nrf24l01+ and will most definitely test it when I get my hands on them

I just helped a friend install a Fitbit "Zip" model. In the process of doing that I noticed it is powered by a CR2025 (3V lithium button) battery.
Their ads claim it runs "up to 6 months" on this battery. It communicates wirelessly (ie. Bluetooth) as well as having an LCD screen. It also takes measurements.
Thus, what you are trying to achieve sounds technically possible, as someone has done it.

I can get a few weeks depending upon usage, and I need a few months.

So to solve your problem it would help to know what your existing current consumption is.
I have a project about an ATtiny85 torch locator. That does not do radio transmission but does flash an LED. I calculate the battery should last 3 years, and at this stage (almost a year after I made it) it is still working on the same battery.
You may get some ideas from that link.
I calculated (and confirmed by measurement) that in idle mode it uses 4.4 µA. You should be getting a similar figure during your sleep periods.

I gotta say, that's pretty amazing that it can run for so long on such a small battery with all those radios and displays working. I've got the power up and power down much more efficient - now the peak current draw is less than 5mA or so (my DMM's fuse is blown so I can't read it accurately). The main purpose of this question was to see if there was a better option than battery power, but the general consensus seems to be that most things will require quite a bit of experimentation and to work. Thanks for your help.


text:
Watchdog approach
I'm developing up a project that is designed to run 24/7 (an energy monitor) logging via wifi.
Due to a variety of considerations I've ended up with a design that links an Arduino Nano with an ESP8266-01.
I was considering designing in a watchdog, but had the thought that each of these MCUs could act as the watchdog for the other.  My hypothesis is that the likelihood of both going down simultaneously is relatively low, and as both need to communicate with each other regularly, they will know when the other unit has become non-responsive, and they would also be able to initiate a hardware (rather than software) reset on the other device.
Is this a valid/workable approach?  Or is there something else I need to consider that would warrant an external watchdog(s)?
EDIT: as there were a few comments re: low-power etc., just wanted to clarify that this will be powered from the 240v supply it monitors (using a switch-mode supply), so this isn't expected to be an issue.

If you have not already taken a look at WickedDevice WildFire external watchdog approach I do recommend that: http://shop.wickeddevice.com/resources/wildfire/

Thanks Mikael—I had spotted that device, but I'm aiming for a lower overall cost of the unit for this project.  It's a nice bit of kit and I suspect will simplify a lot of things for future work/prototyping...

See my amended reply about devices powered from the mains.

I believe both MCU have hardware watchdog timers build into them. I don't see any real advantage in your method. Neither do I see any disadvantage, other than more work to implement. You'd have to run some custom code on the ESP, as opposed to just stock firmware.

I had a similar project a while back, including the desire for the watchdog.

My hypothesis is that the likelihood of both going down simultaneously is relatively low ...

Here's the problem. If it is solar powered (or even just battery powered) then the likelihood is quite high that they will both get insufficient power at much the same time (ie. low voltage).
One thing I noticed was that if voltage slowly drops (as it does when the sun goes down, and the battery discharges) then the processor can enter a brown-out situation where it basically just goes dead, without resetting.
Now you can set brown-out detection in the fuses, but the reference voltage generator, needed to make it work, itself increases the power consumption. So you get the situation where the brownout detection drains the battery, causing a brown-out situation, where without brownout detection it might have lasted all night.

Anyway, the net effect was that the design on the linked page wasn't as reliable as I hoped.
To make this answer more complete, here is my watchdog processor schematic:

And this was the code for it:
// Reset solar panel watchdog
// Author: Nick Gammon
// Date: 22 March 2015

// ATMEL ATTINY 25/45/85 / ARDUINO
// Pin 1 is /RESET
//
//                  +-\/-+
// Ain0 (D 5) PB5  1|    |8  Vcc
// Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
// Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
//            GND  4|    |5  PB0 (D 0) pwm0
//                  +----+

/*

 After reset waits for TIME_TO_WAIT minutes, then brings D0 (pin 5) high for long
 enough to activate a MOSFET and reset the other board.

 Fuses: Low: E2 High: DD

 (Brownout at 2.7V)

*/

#include <avr/sleep.h>    // Sleep Modes
#include <avr/power.h>    // Power management
#include <avr/wdt.h>      // Watchdog timer

const byte MOSFET = 0;          // pin 5
unsigned long counter = 0;

const float TIME_TO_WAIT = 30; // minutes
const unsigned long SLEEPS_TO_WAIT = TIME_TO_WAIT * 60.0 / 8.0;  // 8 second sleeps

// watchdog interrupt
ISR (WDT_vect)
  {
   wdt_disable();  // disable watchdog
  }  // end of WDT_vect

#if defined(__AVR_ATtiny85__)
  #define watchdogRegister WDTCR
#else
  #define watchdogRegister WDTCSR
#endif

void setup ()
  {
  wdt_reset();
  pinMode (MOSFET, OUTPUT);
  ADCSRA = 0;            // turn off ADC
  power_all_disable ();  // power off ADC, Timer 0 and 1, serial interface
  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  }  // end of setup

void loop ()
  {
  counter++;

  if (counter >= SLEEPS_TO_WAIT)
    {
    digitalWrite (MOSFET, HIGH);
    delayMicroseconds (10000);
    digitalWrite (MOSFET, LOW);
    // our job here is done
    sleep_enable ();       // ready to sleep
    sleep_cpu ();          // sleep
    }

  goToSleep ();
  }  // end of loop

void goToSleep ()
  {
  noInterrupts ();       // timed sequence coming up
  // pat the dog
  wdt_reset();

  // clear various "reset" flags
  MCUSR = 0;
  // allow changes, disable reset, clear existing interrupt
  watchdogRegister = bit (WDCE) | bit (WDE) | bit (WDIF);
  // set interrupt mode and an interval (WDE must be changed from 1 to 0 here)
  watchdogRegister = bit (WDIE) | bit (WDP3) | bit (WDP0);    // set WDIE, and 8 seconds delay

  sleep_enable ();       // ready to sleep
  interrupts ();         // interrupts are required now
  sleep_cpu ();          // sleep
  sleep_disable ();      // precaution
  }  // end of goToSleep

The design intention here was that the watchdog processor would reset overnight (when the solar panel lost power and the supercapacitor eventually discharged) and in the morning it would power up, wait 30 minutes (for the sun to rise and the voltage to become stable) and then unconditionally reset the other processor from whatever state it was in.

as there were a few comments re: low-power etc., just wanted to clarify that this will be powered from the 240v supply it monitors (using a switch-mode supply)

Yes, well I also live in a country with 240V power. Today during 41°C heat the power failed a number of times for very short intervals. Various computers reset or behaved strangely. Like with a low voltage battery, a brown-out, or brief failure, of the mains power could simultaneously strike all your devices, including the watchdog device.

As a watchdog mechanism to protect against software lockup type issues then using one processor to detect issues and reset the other is an economical idea.  However, I would completely agree with Nick that if you want protection from hardware issues like brown outs or slow rise time of the power supply then both micros could share the same vulnerabilities that a dedicated watchdog device would be able to address.  How significant this is depends on your power arrangements.
The other case to consider is now much does the software of one device interact with and depend on that of the other device such that it is conceivable that one device locking up in some way could impact the other defeating the watchdog functionality.
Personally I've seen too many situations where an internal micro watchdog failed to detect and recover an issue so would always go for an external device in any professional product.  Even there I would advise the use of a devices which requires the watchdog to be kicked within a time window rather than just within a maximum time period - otherwise if things contrive to go wrong in such a way that the watchdog is permanently getting kicked it will not recover the situation.  [I saw the micro pin responsible for kicking a simple external watchdog accidentally reconfigured by runaway code as a timer output once.]
I suspect that if you are thinking that your product needs a watchdog then it is worth doing properly with an external one.

authors: ทศพล ไทรรักยม


text:
Serial Communication Between Two arduinos (Asking and Receiving)
Can anyone help? I'm trying to develop two sketches, where data can only be sent when a request is made for it between two arduinos. A simple hello world message can suffice. I tried out the Serial Ascii Call and Response on the arduino IDE but it didn't work for me???. Do find below the code sketches
//Arduino Sketch 1
uint16_t alpha;
uint16_t lambo;
Banana nanas;    //to hold the Banana object
uint16_t dataArray[2];
void Setup(){
    Serial.begin(9600);
    establishContact();
}

void loop(){
    alpha=nanas.getRad;
    lambo = nanas.getBars;
    dataArray[0] = alpha;
    dataArray[1] = lambo;
    Serial.write((uint8_t*)dataArray, sizeof(dataArray));
    Serial.flush();   //clear the serial port
}

void establishContact()
{
    if (Serial.available())
    {
        while (Serial.available()  > 0)
        {
            int newByte = Serial.read();
            if (newByte == 'Q')
            {
                Serial.write(newByte);
                Serial.flush();
            }
        }
    }
}

The sketch for the other arduino is shown below
//Arduino sketch 2
static char buffer[2];
void setup(){
    Serial.begin(9600);
    Serial1.begin(9600);
    establishContact();
}
void loop(){
    if(Serial1.available())
    {
        while(Serial1.available() > 0){
            uint16_t gondola1 = Serial1.read();
            uint16_t gondola2 = Serial1.read();
            uint16_t crixus = gondola2 >> 8;
            crixus = (crixus | gondola1);

            gondola1 = Serial1.read();
            gondola2 = Serial1.read();
            uint16_t mario = gondola2 >> 8;
            mario = (mario | gondola1);
            buffer[0] = crixus;
            buffer[1] = mario;
            Serial.write(buffer, sizeof(buffer);
            Serial1.flush();
        }
    }
}
void establishContact(){
    if (Serial.available()){
        uint16_t newByte = Serial.read();
        if(newByte == 'Q')
        {
            Serial.flush();
            Serial.write(newByte);
        }
    }
}

Please elaborate.
What boards do you use?
What libraries do you use?(code does not compile as it is)
What connections you have made between the boards?
Also, I cannot really understand what exactly you want to happen when which board recieves what from the other board? Send a message back to the sender's board? Send a message elsewhere?

@foivaras..the boards in question are an arduino uno which the sensor is connected to and an arduino mega which is used to receive the data being sent, The connections are the usual tx/rx from the uno to serial1 on mega. there are no other libraries included. The Mega request for data from the uno..uno sees the request command and then sends data .. mega receives data and request for more data. Thats it in a nutshell

if you do not use any library then your code does not compile.
Sketch one has an undeclared Servo type.
Sketch two gives a redeclaration of uint16_t gondola1 error.

@foivaras the Servo class I used is just a random name I adopted ...in hindsight I should have changed it to something else..i just wanted to show that there is a class that an object can be declared from,  to call its respective methods. I'll edit the sketches out now

Setup() should be setup() in the first sketch? What exactly is Banana? Why complicate things, if all you want to do is send 'Hello world' on request? If that isnt your goal, then edit your post and say exactly what the sketches are for and exactly what you mean by it didn't work for me.

it is not really easy to follow your code but here is a "hello world" procedure to do an on demand data send between two arduinos:

upload this code to arduino uno before you make any connection on pins 0 and 1 of the board:
/**
 * Code for server side (arduino uno)
 */

uint8_t data2send = 'A'; //data to send on a received request
uint8_t incomingByte;

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

void loop() {
        // send data only when you receive data:
        if (Serial.available() > 0) {

                // read the incoming byte:
                incomingByte = Serial.read();

                if(incomingByte=='Q'){  //if incoming data is the expected request (request code = 'Q' in this example)
                        Serial.write(data2send);
                }
        }
}

connect:
UNO  | MEGA
------------
pin0 | pin18
pin1 | pin19
GND  | GND

upload to arduino mega this code:
 /**
 *  code for arduino mega.
 *
 *  proxy between Serial0 and Serial1
 *
 *  send data to Serial0 to forward it to Serial1.
 *  when data is received from Serial1 it will be forwarded to Serial0.
 */

void setup() {
        // initialize both serial ports:
        Serial.begin(9600);
        Serial1.begin(9600);
}

void loop() {
        // read from port 1, send to port 0:
        if (Serial1.available()) {
                int inByte = Serial1.read();
                Serial.write(inByte);
        }

        // read from port 0, send to port 1:
        if (Serial.available()) {
                int inByte = Serial.read();
                Serial1.write(inByte);
        }
}

open the mega's serial monitor and send some characters. Check that you receive back data only when you send a 'Q' character.

generally speaking, if a given answer is satisfying you then you should mark it as accepted.
See also faq about accepting answers. Thank you.


text:
How do I change the default number of parameters SDI 12?
I am a nooby so this might be an obvious answer kind of a question, but how do I change how many parameters arduino-uno reads from a sensor using SDI communication? My code (which was in public domain, an example for SDI communication) has no problems taking 3 or less parameters but the probe I have has 7 sensors in it and I need all of their values (but all I get in return is 1, literally just the number 1). If I remove and leave only 3 sensors in the probe it works normally. So the problem is not in the communication but in the quantity of data. My code:
    #include <SDISerial.h>
    #define DATALINE_PIN 2
    #define INVERTED 1

    SDISerial sdi_serial_connection(DATALINE_PIN, INVERTED);

    char* get_measurement(){
     char* service_request = sdi_serial_connection.sdi_query("?M!",60000UL);
     char* service_request_complete = sdi_serial_connection.wait_for_response(900);
     return sdi_serial_connection.sdi_query("?D0!",60000UL);
    }

    void setup(){
     sdi_serial_connection.begin(); // start our SDI connection
     Serial.begin(9600); // start the connection
     Serial.println("OK INITIALIZED"); // startup string
     delay(90000); // startup delay to allow sensor to powerup, 1.5 min
    }

    void loop(){
     char* response = get_measurement(); // get measurement data

     if (response!=NULL && response[0] != '\0')
      Serial.println(response);
     else
      Serial.println("No Response");
     delay(1500);
    }

Check the timeout values. 60000 should be 60000UL as the parameter is defined as uint32_t. The statement "uint8_t wait_for_response_ms = 180000" is also very wrong but not used. Same goes for "int j=0". Please clean up the code.

get_measurement(); is called only once in loop().

get_measurement(); within the loop is just fine, it does continuously call for the values even though it is not in classical form of a loop -again, this is a public code which i just tweeked a little to fit my needs.
However, the rest of the suggestions were spot on and thank you for that, even though it does not solve my problem it does speed up the execution.


text:
Will this AC-DC converter chip really work with arduino?
I am looking for a compact solution to convert some 220V/20amp AC to something edible by our arduinos (like 5V/2amp DC). I would like to plug directly my arduino to the wall. I found many things like some Hi-link (HLK-PM01) chips ... But I also found this one :

LNK564DN - US $0.34 / piece
LNK564DN - US $1.14 / piece

That seems perfect, but unfortunatly, I can not find any tuto or example of use for this, shipping included, really cheap chip.
The datasheet is here.
What do you think about it ?

" I would like to plug directly my arduino to the wall." - Why? What for?
If you want to power the Arduino you could use one of these. If you want to sense 220VAC try this.

Where will you source the transformer from?

The goal is to create a compact prototype which can be pluged into the 220v (France) wall plug. Don't you think the LNK564DN should do the job to give the prototype the current it needs ? Thanks.

The LNK564DN is the controller for a power conversion circuit.  To use it, you also need four diodes, four capacitors, three resistors, a special transformer, and a circuit board. You can get an "AC 100-240V 0.3A DC 5V 2A EU Plug USB Power Supply Adapter Charger" on Ebay for $1.74 with free shipping.

@Charaf What EXACTLY are you plugging into the 220VAC? I mean exactly what pins?

@James 200VAC plug -> AC-DC converter -> Arduino nano -> HC-06 + ESP8266. I am trying to put all of this in a simple compact case.

@jwpat7 Thank you ! I thought it was as simple as the hlk-pm01 =)

So you are powering the nano not sensing the 220VAC. Like @Jake C told you: It's dangerous. We use an off the shelf power supply, or a wall adapter. That's the best solution but it's over to you whether you take the advice.

What do you think about it ?

If you have to ask, don't do it. Mains voltage can be dangerous and should only be done if you know what you are doing and how to be safe. The best choice is to just use pre-built adapters from reputable sources.

It is a good advice. Thank you. But I think I can take the risk, it's for learning purposes =)

Buying random chips from China and asking on internet forums is not the best way to be learning about how to work with mains voltage.


text:
I'm pretty sure I fried my Arduino Uno. Given my setup, what caused it to be fried? (I can't identify the short)
I was trying to drive a Nema 17 stepper motor using an arduino uno and an A4988 driver. I had it wired up according to this instructable (http://www.instructables.com/id/Drive-a-Stepper-Motor-with-an-Arduino-and-a-A4988-/) at step 2 without the motor power supply wired to the bread board yet. ALSO, I hadn't wired the sleep to reset yet (I just didn't read directions carefully). The board was connected to my computer via USB and I had uploaded the sketch on the instructable to it.
Then, because I misunderstood the directions, I plugged my 12V 8A power supply into the power input on the arduino. All of the sudden, my computer turned off. My computer is fine after restarting, but now the arduino isn't recognized at all by the computer when I plug it in.
Given this information, I am pretty sure that my arduino is fried. However, I can't understand why plugging in the power supply to the power input, which has a voltage regulator, would cause the board to fry.

That's an odd problem. If you power the arduino from a 9V/12V power supply to the jack on the board, with no USB connected, test the arduino chip and the voltage regulator with your finger; do they get hot to the touch? That's the best indication that one has fried.

When I look at picture 2 of step 2, there is a connection Vin of the Arduino to the motor power. On the picture 3 this is missing. How was your cabling?

Are you absolutely sure you used the RAW pin and not the VCC pin?

Do any other usb devices work?

I had tested other devices and know that neither my computer nor the cord are the issue.

The board doesn't get hot when I plug it in now, BUT it was hot right after the incident. Like I said, I'm pretty sure its fried, I'm just trying to figure out why so I don't do it again.

@ott-- Interesing, I did not have anything wired to vin.

@PandaLion98 does the arduino uno even have a RAW pin? (sorry if its obvious or something; I am new to arduino)

@Jere82 Oh, sorry. It's labeled VIN on an UNO. On Pro Minis, it's labeled RAW.

@Jere82 Where exactly did you connect your "12V 8A power supply"? The Arduino has a lot of power inputs.

Please specify the datasheet for the stepper motor.

@PandaLion98 I connected it through the barrel plug connector, which to me seems like no problem because of the voltage regulator. Is it possible I got a crappy board with a bad voltage regulator?

I wonder if you destroyed your Arduino's voltage regulator.
If the Arduino was connected to the stepper motor via the A4988 when you powered the Arduino with a 12V supply, the stepper motor might have drawn current from the Arduino's regulator. This current is likely ~2As, which is far more than the tens of milliamps the Arduino is designed to output. This kind of current draw could quite possibly destroy the regulator on your Uno.
This could also explain why your computer restarted. USB ports on computers are designed to provide an output voltage to their USB devices, so if you provide a voltage on the USB power lines your computer is also driving, you can short your ports if the two voltages are not exactly the same. This is actually why USB cables have the A vs B end design - they mark which side should supply power (A), and which should be powered (B). The Arduino might have provided a voltage on the USB cable's 5V line and thus shorted something in your computer that provides the voltage for your USB ports (I believe Unos are not designed to be powered by both USB and the 12V connectors simultaneously).
If the regulator fried on your Uno, you might have had a voltage that was way off of the expected 5v on the USB port. A well designed USB port will usually try protect itself in a situation like this, often causing the computer to shutdown or the USB bus to deactivate until restarting the computer.
You could check your Uno's voltage regulator with a multimeter or better yet and oscilloscope to see if that is in fact the problem. If so, you could solder a new one on pretty cheaply and quickly. However, there is no guarantee nothing else got fried, in which case buying a new $10-20 Uno looks like a pretty appealing option.

The Uno is not one "thing" that fails. It has various components, some of which may have failed. I wrote a lengthy page about how to test various parts:
Have I bricked my Arduino Uno? Problems with uploading to board

I plugged my 12V 8A power supply into the power input on the arduino.

Perhaps you reversed the leads, and shorted the USB power to ground, thus causing the PC to turn off? This would probably also blow most of the components on the Uno because they would have had -12V applied to them, assuming it got past the voltage regulator.
However there is a reverse polarity protection diode on the power input jack. Did you use that or the Vin pin? (or the Vcc pin?)
Note that the reverse polarity protection does not protect you if you use the Vin pin.

Thanks for the info page. What do you mean by reversing the leads? I used the 2.1 mm center-positive barrel plug connector on the arduino so wouldn't that be impossible? Also, I didn't have anything wired to the vcc pin, and the Vcc pin was wired to the input voltage on the stepper motor driver.

You said I plugged my 12V 8A power supply into the power input on the arduino. I assumed you had to make up a lead for a heavy-duty power supply, and might have got them the wrong way around.


text:
Raspberry Pi Arduino Installer broken
I am tring to use ShorTie8's new arduino ARM installer on my RPI B+ by copying this into my terminal:

cd
sudo apt-get update -y && sudo apt-get dist-upgrade -y
wget https://raw.githubusercontent.com/ShorTie8/Arduino_IDE/master/Arduino_IDE_builder.bash
chmod +x Arduino_IDE_builder.bash
sudo ./Arduino_IDE_builder.bash
sudo Arduino/build/linux/work/./arduino
sudo Arduino/build/linux/work/./install.sh
sudo apt-get install -y mercurial subversion build-essential gperf bison ant texinfo zip automake flex libusb-dev libusb-1.0-0-dev libtinfo-dev pkg-config libwxbase3.0-dev libtools

But Getting The following Error at sudo ./Arduino_IDE_builder.bash

echo -e '\n\nConfiguration values\n\n'

Configuration values

Stable=1.6.7
Update_me=yes
Silence_is_Golden=yes
echo -e '\n\nSystem check\n\n'

System check
++ date
  + start_time='Sat 13 Feb 11:12:37 GMT 2016'
  ++ pwd
  + Start_Directory=/home/pi
  ++ pwd
  + Working_Directory=/home/pi/Arduino/build
  + echo -e '\n\nChecking for root .. \n'
Checking for root ..
++ id -u
  + '[' 0 '!=' 0 ']'
  + echo 'Yuppers .. :)~'
  Yuppers .. :)~
  + [[ yes == \y\e\s ]]
  + echo -e '\n\nChecking to see if I'\''m update\n'
Checking to see if I'm update

git remote update
  fatal: Not a git repository (or any of the parent directories): .git

Instead of manually downloading a file from the github repository, check out the repository properly with git clone 《repository》

It is a bash script. How can I edit it without messing up?

Pardon? Who said anything about editing anything? Just clone the github repository like you would with any other github repository. Delete your current bash script, you don't want it.


text:
Arduino Pi-3 Ubuntu MATE not compiling
When I try to upload a script to my Genuino Uno from the Linux ARM distro on genuino.cc/downloads it spits out this during compiling.

avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device

Has anyone got any ideas?
Thanks,
Caleb

Have you performed the correct permissions manipulating commands as detailed in the Linux install instructions for the Arduino IDE?

No I didn't, but after doing so the Arduino IDE works! Thanks a lot.

After following the advice left by Majenko, I went to https://www.arduino.cc/en/Guide/Linux and followed the instuctions at the bottom of the page:
If you get an error Error opening serial port ... you need to set serial port permission.
Open Terminal and type:

ls -l /dev/ttyACM*

you will get something like:

crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0

The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we need is "dialout" (is the group owner of the file).
Now we just need to add our user to the group:

sudo usermod -a -G dialout <username>

where  is your linux user name. You will need to log out and log in again for this change to take effect.


text:
Buzzing on computer speakers when LEDs are on
I have an Arduino Nano connected via USB to a Mac Mini. When the LEDs come on, an external speaker connected to the Mini starts to hum/buzz quite loudly. If the LEDs are turned off, the buzz stops.
The speaker and the Mac mini are both powered independently, and are plugged into one wall socket, while the 5V power supply to the LEDs and the Nano is plugged into a different socket (of the same outlet).
What could be causing the buzz and what are the possible remedies?

WTH is a "fadecandy"?

Changed to Arduino

make sure you run a common ground between the amp and source

@LookAlterno I'm using FastLED, which I believe leverages PWM/analogWrite.

@dandavis This sounds reasonable, but possibly hard to do. Or maybe not. The source is the Mac mini, and both the mini and the amp/speaker are plugged into the same power outlet. Neither the Mac plug nor the speaker power plug have a ground prong. Not sure how I would create a common ground between them.

for a mac mini, you can use a chassis screw, for the 5v stuff you can use the negative rail. On a laptop to receiver setup i have going, I have an alligator clip biting a half-inserted USB plug's meta collar, the other jaw biting a lead from the FM antenna gnd on the back of the receiver. w/o, i get hum, occasional clicks, and pink noise, but as soon as the clip bites, near silence. Shielded cables helped a little, but the ground connection basically fixes the issue completely.

If this is the same project you described in this question(readers: "112 WS2811s in series" causing interference), your external speaker may not be filtered very well against energy radiated by nearby un-shielded wiring. Try a pair of headphones in place of the speaker - does it also buzz? If not, the speaker (system) is probably picking up the interference. If so, the pickup is probably within or near the Mac mini.
You could try a few simple solutions (or at least tests that might narrow the problem):

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

It's not the same project, and I would like to believe the issues are not related (the other one has to do with voltage changes probably due to common power source). However your tests are very helpful. I have significantly upped the LED power supply (from 8A -> 30A) and am pluggin both power supplies into a big old UPS with shielded power and the buzz seems to have gone away.


text:
Is it possible to configure FRAM memory for use as stack and heap?
I'm using the Adafruit I2C FRAM breakout board with my Nano and it works as advertised, but every time I write a variable to this thing I have to use library function calls with addressing. This makes it run slower than I want it to, especially since I'm using the memory to keep camera pixel information and I need to process it quickly.
As user Majenko put it:

A write of a single byte requires 4 bytes in a transaction. That's 4 bytes, 1 start, 4 ack and 1 stop bit. So (4x8)+1+4+1 = 38 bits.
A read of a single byte, with "repeated start", requires 5 bytes per transaction, with 2 start, 4 acks, 1 nack and 1 stop. That's (5*8)+2+4+1+1 = 48 bits.
So for a read and write it's 38+48 = 86 bits.
Therefore you'd require 86*512 I2C clock cycles to transfer all 512 bytes in both directions - that's 44032 clock cycles.
At 400,000 bits per second it is 44032/400000 = 0.11 seconds, or 110ms of the time spend transferring data, not counting the time it takes to actually process and prepare the data, fill registers, look for status flags, etc.
If it is taking half a second then at 400,000 bits per second you have 44032 / (400000/2) * 100 = 22% of the time it's actually transmitting or receiving data over I2C.

It's much faster to write entire arrays at a time, but I need to write the data int-by-int as the data is encountered, since my whole reason for using the breakout board was to avoid needing local buffer space.
So is it possible to somehow configure this so that my I2C bus writes to the FRAM memory autonomously just like it does with the stack/heap in the onboard SRAM memory? Because then I could just declare my arrays as normal and let the processor take care of it, and then I would be so happy.

Have you looked into FRAM with an SPI interface, which may be capable of higher transfer speeds than I2C?

Thanks. Yes I have, but the small difference is only in write and read speed. 75% of the time I'm spending is actually taking care of the bookkeeping. Also, I'm already Using my SPI pins for an LCD screen.

No, you can't use SPI or I2C memories to store stack or heap data in AVR microcontrollers, as the AVR MCUs do not allow to map memories connected to the SPI or I2C buses. In other words, there is no way to tell the MCU that you connected a SPI or I2C memory, and how to use it, automatically. Therefore you can only use such memories to manually store/read data, by manually issuing all the correct command sequences, which will be very slow (as you wrote you are already doing by calling some libary functions).
Instead, you can use an external PARALLEL memory, connected to the external memory bus, which is present on SOME AVR microcontrollers (unfortunately, the ATMEGA328 has no external memory bus). Still you'll get a much slower performance with respect to the internal memory.
Finally, Arduino is not a  good platform to process (or store/read) pixel data from a camera, due to severe computing power and memory limits. Even if there are more powerful Arduino (or Arduino-compatible) boards, which feature much more powerful processors (e.g. Cortex M3 or M4), you would probably need to program them using a very optimized C (and not C++!) code, or even ASM. But at this point, there would no reasons to use an Arduino-compatible platform, instead of an another one, possibly much more powerful or even cheaper.

There's nothing wrong with using C++ for this application provided the C++ libraries used are non-terrible.

@IgnacioVazquez-Abrams for this application, using a powerful MCU with a good amount of RAM, yes. For a "tiny" MCU, you should save as many resources as possible. (besides, many - not all - Arduino C++ libraries are unfortunately terrible..)

Thanks, @next-hack. If I really have to, I'll just move up to a Mega and make my device larger (not happy about this). Arduino is fine for this particular camera application, since It's only a monochromatic linear CCD with just 128 pixels. It actually worked pretty great until I added more peripherals and started to run out of volatile memory.

Yes it is possible to have c variables use external RAM. The Atmel AVR FAQ discusses this. It's also possible to have the heap and stack (not recommended but possible), use external RAM.
Bear in mind that having this dealt with autonomously is still going to take roughly the same amount of time as it's going to have to execute similar functions to the ones you list above, albeit without having to code the transactions.
Have you considered a mega, and cache 1-6k of data then transfer that all at once. Using SPI would be faster, even more so with 1-6k. You can have an SPI LCD and RAM off the same pins, they just need an additional digital pin for the second device.

The "external RAM" discussed in that FAQ requires an actual external memory bus such as found on the ATmega64. There is no chance that it will work with a Nano, and certainly not over I2C.

Not even on SPI.

I don't have experience with FRAM, but below are some results with SRAM: 23LC1024 (128 KB SRAM with SPI). Tests have been performed with an Arduino Uno.
(I had to use an answer instead of a comment because of the (screenshot) table alignment.
As you can see, write/read of a page (32 bytes) is faster than other types, but it depends on the amount of bytes you have to write to use pages.
(Because I want to use reasonable complex structures, I decided to go for a microcontroller with more RAM because stack and heap space cannot be used from external SRAM).


text:
I seem to be having trouble with these libraries and the Arduino 101. Can anyone look at my output and tell me what I should do?
I'm not finding many resources out there. I already tried using new versions of "TFTv2.h" and "TFTv2.cpp", but I don't think much of anything changed in my output.
These are the libraries I'm trying to use. The sketch I'm trying to compile for the 101 is empty except for these lines and an empty setup() and loop().
#include <stdint.h>
#include <TFTv2.h>//For Seedstudio Touch
#include <SPI.h>
#include <SeeedTouchScreen.h>   //Seedstudio LCD touch screen Library File
#include <SD.h>//For Seedstudio Touch
#include <XBee.h>   //Zigbee Wireless transciever Library File
#include <Printers.h>   //Zigbee Wireless transciever Library File

Basically I need to know whether I need to find replacements or workarounds for these libraries. Compiling for the 101 in Visual Studio, I get a lot of output messages that I don't get when compiling for the Mega. I have more-or-less no idea what they mean.
I'll go ahead and paste the non-verbose output here. Thanks for your advice! Let me know if I should add the verbose output, and I'll post it right away.
output (non-verbose);
Compiling debug version of 'Arduino_101trial' for 'Arduino/Genuino 101'
Sd2Card.cpp:In member function 'uint8_t Sd2Card::readData(uint32_t, uint16_t, uint16_t, uint8_t*)
Sd2Card.cpp:379:12: warning: unused variable 'n' [-Wunused-variable]
:uint16_t n
SdFile.cpp:In static member function 'static uint8_t SdFile::make83Name(const char*, uint8_t*)
SdFile.cpp:261:15: warning: unused variable 'b' [-Wunused-variable]
:uint8_t b
SdFile.cpp:In member function 'uint8_t SdFile::rmRfStar()
SdFile.cpp:907:40: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
:if (curPosition_ != (32*(index + 1))) {
TFTv2.cpp:In member function 'void TFT::drawString(char*, short unsigned int, short unsigned int, short unsigned int, short unsigned int)
TFTv2.cpp:388:18: warning: value computed is not used [-Wunused-value]
:*string++
SeeedTouchScreen.cpp:In file included from
pins_arduino.h:39:14: error: 'uint8_t' does not name a type
:static const uint8_t SS   = 10
pins_arduino.h:40:14: error: 'uint8_t' does not name a type
:static const uint8_t MOSI = 11
pins_arduino.h:41:14: error: 'uint8_t' does not name a type
:static const uint8_t MISO = 12
pins_arduino.h:42:14: error: 'uint8_t' does not name a type
:static const uint8_t SCK  = 13
pins_arduino.h:44:14: error: 'uint8_t' does not name a type
:static const uint8_t SDA = 18
pins_arduino.h:45:14: error: 'uint8_t' does not name a type
:static const uint8_t SCL = 19
pins_arduino.h:46:14: error: 'uint8_t' does not name a type
:static const uint8_t LED_BUILTIN = 13
pins_arduino.h:48:14: error: 'uint8_t' does not name a type
:static const uint8_t A0 = 14
pins_arduino.h:49:14: error: 'uint8_t' does not name a type
:static const uint8_t A1 = 15
pins_arduino.h:50:14: error: 'uint8_t' does not name a type
:static const uint8_t A2 = 16
pins_arduino.h:51:14: error: 'uint8_t' does not name a type
:static const uint8_t A3 = 17
pins_arduino.h:52:14: error: 'uint8_t' does not name a type
:static const uint8_t A4 = 18
pins_arduino.h:53:14: error: 'uint8_t' does not name a type
:static const uint8_t A5 = 19
pins_arduino.h:55:14: error: 'uint8_t' does not name a type
:static const uint8_t ATN = 20
Arduino.h:In file included from
wiring_private.h:from
SeeedTouchScreen.cpp:from
SeeedTouchScreen.cpp:In member function 'Point TouchScreen::getPoint()
SeeedTouchScreen.cpp:94:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(yp_port) &= ~yp_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:95:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(ym_port) &= ~ym_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:100:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(xp_port) |= xp_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:101:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(xm_port) &= ~xm_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:127:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(xp_port) &= ~xp_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:130:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(yp_port) |= yp_pin
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:153:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(xp_port) &= ~xp_pin;            \\ Set X+ to ground
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:154:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(ym_port) |=  ym_pin;            \\ Set Y- to VCC
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
SeeedTouchScreen.cpp:155:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
:*portOutputRegister(yp_port) &= ~yp_pin;            \\ Hi-Z X- and Y+
variant.h:in definition of macro 'portOutputRegister
:#define portOutputRegister(port)  (uint32_t*)port
Error compiling libraries

@Gerber- Thanks for fixing my formatting!

So it looks like you have some warnings in Sd2Card.cpp, SdFile.cpp, TFTv2.cpp
For the most part you can ignore these warnings
As for SeeedTouchScreen.cpp it looks like you're getting Errors for pins.
does not name a type means that uint8_t is not a type Visual Studio understands.
Then further down you're getting another warning for SeeedTouchScreen.cpp
cast to pointer from integer of different size
Did you make sure that whatever board you're using is compatible with these libraries?

The Arduino Mega has 54 digital input/output pins (of which 14 can be used as PWM outputs), 16 analog inputs, 4 UARTs (hardware serial ports)
The 101 comes with 14 digital input/output pins (of which 4 can be used as PWM outputs), 6 analog inputs.
This means that if your libraries are designed for the Mega and no other board you will run into these errors

I think you're right, because despite some other loading issues which I now believe are unrelated (waiting for board and port reconnecting), I was finally able to compile and load a simple sketch.
The one thing I had to do was comment out SeeedTouchScreen.h, so I suppose it did ignore all of those other issues.
I'm now looking for a new version of this library, but if it has something to do with the pins, perhaps i can improvise a solution and modify the existing library. Perhaps I'll submit a pull request!

authors: มีสุข ทุกวัน


text:
Time Stamping data on an Arduino and reading it on a Java IDE
Does anyone have an idea on the best way to time stamp an arduino sketch that contains a data packet which is to be read out using a java IDE (IntelliJ) for graphic visualization of the packet. I tried declaring the time variable on the arduino section but having problem unpacking the unsigned long variable in java. Below is a snippet of the arduino code.
             unsigned long codeTime = 0; //The time the sketch takes to execute
         static unsigned long char dataArray [1]; // a variable to hold both sensor data

         void setup(){
              Serial.begin(9600);
              Serial1.begin(9600);
          }
         void state1(){
             if (Serial1.available()){
                    while (Serial1.available() > 0){
                 codeTime = millis(); //using the millis() instead of micros()
                 //memcpy should copy the whole data into position 0 ????
                 memcpy(&dataArray[0], &codeTime,sizeof(codeTime));
                 uint16_t newByte1 = Serial1.read(); // read in the first byte
                 uint16_t newByte2 = Serial1.read(); //read in the second byte
                 uint16_t dataByte = newByte2 >> 8;
                 dataByte = (dataByte | newByte1);
                 dataArray[1] = dataByte;
                 Serial1.write((uint16_t*)dataArray, sizeOf(dataArray));
                 }
               }
              }

            void loop(){
                   state1();
                   Serial1.flush();  //clear the serial port
                   delay(100);
                }

The question now is how do i unpack the data in java to ensure that the time variable (unsigned long time variable is well unpacked in the correct order)????. The second variable i could easily unpack in java as
              int variable1 = variable2 >> 8; //as it is a 16 bit integer I shifted
                                              // the msb/lsb accordingly
              variable1 = (variable1 | variable2);  // and finally casting it.

I don't see in your code where you are actually sending the time through serial.

@majenko I saved the time variable 'codeTime' in position zero in the buffer (buffer[0]).. and i wrote both data through to serial using Serial.write(buffer,sizeof(buffer));

I don't see that in your code.

@majenko  I just saw the mistake.. fixing now

There's a number of fundamentally wrong things in your sketch.
static char buffer[1]; // a variable to hold both sensor data

No - that has room for 1 entry - hence the 1. 1 means 1, not 2.
buffer[1] = newByte;

No. There is no buffer[1]. You count slices from 0.  buffer[0] exists (the first one) but buffer[1] doesn't.
buffer[0] = millis;

You aren't calling the function, you are assigning the address of the function. And worse than that, buffer is an array of 8-bit values - neither the address of the function, nor the return value from the function (if you were to fix that) would fit in that space - since the return value is an unsigned long which is 4 bytes in size.
You need to have at least 5 bytes in your array - four for the time stamp and one for the value you read from serial. Then you place them in to the array in the order you see fit, and read them back in the same order in Java.

i replaced the buffer with a 16 bit array that could comfortably contain all 4 bytes but the problem still persist

In what universe can you fit a 32 bit value and an 8 bit value into a 16 bit array with 1 slice? You can't count, can you?

was a little bit buggered there, got that fixed now, is that fine by you??

No. You still can't count. Where is your dataByte going? Scrap the array. Don't use it. There's no point. Just send the 6 bytes you need to send as bytes. That is, split your unsigned long into 4 bytes sending each one as you go (bit-shift and mask), then you data bytes. 6 bytes. That is all. And then work out how you are going to know at the other end which byte is which. Your whole methodology is flawed. You have no protocol, only raw data.


text:
expected class-name before '{' token
I am getting the following error when attempting to compile my sketch:

In file included from sketch.ino:24:0: SerialRenderer.h:7: error:
  expected class-name before '{' token

SerialRenderer.h
#ifndef SERIALRENDERER_H_
#define SERIALRENDERER_H_

#include <MenuSystem.h>

class SerialRenderer : public MenuComponentRenderer
{
public:
    SerialRenderer();
    virtual ~SerialRenderer();

public: // methods from MenuComponentRenderer
    virtual void render(Menu const& menu) const;
    virtual void render_menu_item(MenuItem const& menu_item) const;
    virtual void render_back_menu_item(BackMenuItem const& menu_item) const;
    virtual void render_numeric_menu_item(NumericMenuItem const& menu_item) const;
    virtual void render_menu(Menu const& menu) const;
};

#endif // SERIALRENDERER_H_

The contents of MenuSystem.h can be found at https://github.com/jonblack/arduino-menusystem/blob/master/MenuSystem.h.
It seems like the include of MenuSystem.h does not happen when SerialRenderer.h is included from my main sketch file. I get the same error if the include in SerialRenderer.h is removed.
Is there something simple I am missing for the compiler to be able to "see" MenuSystem.h?
EDIT:
Turns out I was looking at a newer version of the arduino-menusystem library than I had installed (version 2.1.1). That version did not have a class called MenuComponentRenderer.
I pulled the latest version from https://github.com/jonblack/arduino-menusystem/tree/master and it compiles fine.

It is most likely caused by the fact that a correct version of MenuSystem library is not properly installed.
Check whether you can add the library to your sketch.
EDIT: added that also the version should be correct

I can include the library in my sketch via Sketch > Include Library. Also Library Manager shows that version 2.1.1 is installed.

Rembember to add the include to the sketch. The build will look at the sketch includes to add the necessary paths.

@MikaelPatel My main sketch is including both SerialRenderer.h and MenuSystem.h, but I get the same error whether or not MenuSystem.h is included.

Indeed the version is also important.