text:
I2C communication between arduino and raspberry pi breaks under stress for unclear reasons. Why?
I am having a behavior I cannot explain while using arduino mega as a I2C slave for a raspberry pi master.
I am showing here an idealised program that shows the issue. I experience pretty much the same behavior in the real application (a keyboard firmware). What I am doing is the following:

the arduino issues an interrupt on pin 23 at evert loop to inform the raspi that there's some data to be read.
the raspi sends a request as master to the arduino.
arduino receives the request in the Wire handler, and issues a reply of 32 bytes. I fill these 32 bytes with a uint8 counter just as a check.
the cycle starts again.

This is the code for the raspi
import time
import RPi.GPIO as GPIO
import smbus

GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

bus = smbus.SMBus(1)
address = 0x42

def callback(channel):
    data = bus.read_i2c_block_data(address, 0x00, 32)
    print(data)

GPIO.add_event_detect(4, GPIO.RISING, callback=callback)

while True:
    time.sleep(1)

GPIO.cleanup()

and this is the code of the arduino
#include <Wire.h>

byte IRQ_PIN = 23;

volatile unsigned int counter;

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

    pinMode(IRQ_PIN, OUTPUT);
    digitalWrite(IRQ_PIN, LOW);
    Wire.begin(0x42);
    Wire.onRequest(requestEvent);
    Wire.onReceive(receiveData);

}

void signalMaster() {
  noInterrupts();
  irq();
  interrupts();
}

void irq() {
  digitalWrite(IRQ_PIN, HIGH);
  digitalWrite(IRQ_PIN, LOW);
}

void requestEvent() {
  byte buf[32];
  counter++;
  memset(buf, counter, 32*sizeof(byte));
  Wire.write(buf, 32);
}

void receiveData(int byteCount){
  while(Wire.available()) {
    Wire.read();
  }
}

void loop() {
  signalMaster();
  delay(1);
}

As you can see, the point is that I am banging the I2C really, really fast, and the loop is very tight and fast. This is the point of the exercise and the problem to solve arises from this.
Now, once in a while I get an occasional IO error with the raspi python code. This code occasionally fails once, and then everything resumes to normal, but once in a while, it completely breaks down and never recover.
I attached a logic analyser to it, and this is what I found. D3 is the interrupt pin. The others the I2C bus. In a normal transaction, I can see everything working properly (disregard the different content of the response, it was an earlier run)

and a zoom in to the master request and the reply:

When I have a permanent failure, however, the picture is very different

Zoom in:

This makes little sense to me. Why would it perform a data write, and who is writing 0x85FF... in my buffer?
Thanks

The format is perfectly fine for an actual multi-byte write transaction. It's like the Python library is calling write_i2c_block_data instead of read_i2c_block_data. It must be some bug at the Raspberry end of things, possibly in the py-smbus library.

i'll do some debugging tonight.

@Majenko Ok, from a brief check of the current code, the smbus module is a direct call to i2c_smbus_access, which then just performs an ioctl... so if there's a bug, this goes quite deep. As a curiosity, could the fact that I am using 3.3v vs 5v be a factor? I read conflicting opinions on pairing arduino and raspi without a level shifter in the middle.

The voltage difference wouldn't cause the Pi to perform a completely different transaction.

It might be complete nonsense, but dissabling interupts on the arduino, than triggering the raspi, and than enabling the interupts sets the arduino in a state where it can not react on (now possible) I2C/SMBus interrupts.The raspi is really fast compared to the arduino and there might be a race condition. I admit; I do not believe in this solution myself, but if there no other solution it's worth a try ;-). How do you power/pull up the I2C bus. The resistors might be to high. Your Logic analyzers are no oscis. It shows you the logic levels not the real Voltages.  Th. might also be a problem.

@PeterPaulKiefer I am using an arduino mega 2560 which has internal resistors for the i2c bus. I have an osci as well, so I can give it a check. I must suspend the interrupts as I want to be sure that the interrupt pin is not kept high for a very long time if the ardu is disrupted.

If you power the I2C bus with the arduino than you use 5V (or is it a 3.3V Arduino?). That might destroy your raspi, please be careful with that.
That's also an issue with the interupt PIN 5V is to high for the raspi it might tolerate that for a time, but it is a risk. You can use a voltage divider by two resistors.

The interrupt routines of the arduino should not run for a long time. And, as you react on the rising edge of the interrupt pin on the raspi , it is not a problem if the interrupt pin is high as long as you set it to LOW before the next interrupt. On the other hand, interrupts are necessary for IC2 to work. You could loose information if interrupts don't work, when the raspi started sending before enabling interrupts..

@PeterPaulKiefer Excellent points. I'm going to rework a few things tomorrow evening and see what happens. When it comes to power, currently the arduino is powered via USB, and the raspi via a power supply. So yes, technically they are on different voltages. However, the idea is that both will be powered through the same 5V power supply. Of course the logic levels will not change regardless of the supply. Is a voltage divider resistor enough, or should I use a logic level converter? what is their physical difference?

The 5V from power supply are regulated to the operatng voltage of the Raspi. That's not the same. It's 3.3V.  See Bruno Bronosky's answer.
https://raspberrypi.stackexchange.com/questions/3209/what-are-the-min-max-voltage-current-values-the-gpio-pins-can-handle.

If your signal flows from the higher Voltage to the lower, a Resistor devider might be sufficient. If the signal goes to both directions highV <--> lowV you need a level shifter. If the signal flows from the lower to the higher Voltage and the device with the higher voltage interprets the high Level of the device with the lower Voltage as a high also, you can connect the device directly together if you be sure, that the higher Voltage device never put power on the wire.

What Raspberry are you using? It could be a clock stretchinh problem. I have it too with an Arduino project. If the slave is not able to answer, it try to stretch the clock signal. The Raspberry has some problems with it and once the sync clock is lost both devices will not work anymore... Until you reset the i2c line.

@adriano I am using a pi zero

Not sure, but I think that it is also affected by the clock stretching bug. Once the Arduino stretches the clock, the raspy will loose the synchronisation with your arduino.

Use a logic level conversion IC.

picture source http://msx-elektronika.pl/en/logic-level-converter

I bought two, I'll give it a try this weekend

@StefanoBorini, results?

I added the logic level converter but I still get the same kind of errors. I am unsure at this point what is the reason. I decided that for the time being I just use a traditional keyboard microcontroller, but it's definitely something I have to revisit. I am adding a picture of my setup later tonight

@StefanoBorini, ok. I collected the half of the bounty and two upvotes, so if you now or in the future want to put a bounty on a question, write a comment here and I will put a 50 points bounty on that question (but only if I can't write a useful answer to it :-) )


text:
LED strip with 12v power connected to ESP32
I'm looking at controlling a ws2811 strip and I have seen mention that you should share the same ground between the strip and the controller, which does make sense.
I do not currently have a proper power supply that will supply the full range of 12,5 and 3 volts but what I do have is one of these breadboard power supplies:
https://tinkersphere.com/906-thickbox_default/breadboard-power-supply-module-33v-5v-arduino-raspberry-pi-compatible.jpg
If using a correctly rated 12v power supply into this am I able to take a feed from the 12v line and hook the strip up to that and still have the rest function correctly?
Thanks!

AFAIK the majority of ws2811 strips are powered at 5V; if you have a 12V one this may work, provided that you give the strip enough current (consider 60mA for each LED at 5V, or 60mA for three LEDs if you have the 12V version with 3 LEDs per strip segment)

Its definitely a 12v one (I have measured it to make sure it was not just mislabelled), which caught me off guard given what I had read, it may be because it is a slightly longer strip at 5m. I will work out the draw as you have suggested to make sure. Thank you very much for your answer, exactly what I needed to know!

I have also seen some (older?) strip where there was a WS2811 chip powered at 12V controlling three RGB leds (all the three leds will have the same color); maybe this is yours... like this rigid pcb strip

You are correct, that looks spot on. 3 LED's per chip. This is the strip I have, they were on a dirt cheap offer.  https://www.amazon.co.uk/DreamColor-MINGER-Waterproof-Flexible-Lighting/dp/B0799B8QN7/ref=sr_1_3?ie=UTF8&qid=1543933680&sr=8-3&keywords=dreamcolor

Looking at the picture, you can cut them three at a time, so I think they are the same as the pcb strip I linked (only those ones had wires, while yours is continuous). I think you will see that you will be able to individually address only three leds at a time, rather than each led independently. In any case, if you want to use an arduino you don't need that module; just attach the 12V to the strip, and then power the arduino through the VIN pin (NOT the 5V pin, use the barrel connector or the Vin pin) and, of course, the ground

@frarugi87 he isn't using an Arduino but an EPS32. Depending on which board, it may not have a VIN pin.

12v->3.3v on an LDO driving an ESP32 will get quite hot, maybe hot enough to shut down the 1117-3.3.  Even on the TO-220 version, I need an inch or two of heatsink to keep them under burning hot to the human touch. I would get a cheap adjustable buck converter or a bigger package LDO

Thank you all for your input, ill take it all onboard. I powered the ESP32 from the 5v pin and I managed to get it working last night for a while before the power supply popped and started passing 9v down the 5v output. @dandavis Do these chips also tend to have problems when running 12v to 5v as well or is it just the 3.3v? Either way, I have ordered some new of these cheap supplies as well as a 12v to 5v buck converter. Thank you all for the guidance!

12v to 5v will generate almost as much heat as 12v to 3.3v, so probably.

source: Stack Exchange

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

sort: votes


text:
Sending file from PC to Arduino
How can i send a (file) from PC to Arduino Yun at running time ?
There's a way to send some commands via Serial.
But how would a whole file goes ? Assuming the file can take place at RAM without any problems.
Thanks

Please be precise about what type of file and content.

Just use scp...

@leoc7 image file. JPEG extension.

@Majenko can you guide me to a link or a library ?

What OS are you using? And what do you want to do with the file?

I am using Windows10 @Majenko .

And what do you want to do with the file?

To send it to Internet via Yun. This is a firm part of the Project.

I don't understand. You want to send a file to the Yun from your PC to then send it on to "The Internet"? Why can't you just send it to "The Internet" direct from your PC?

It's a new challenge we are seeking to solve, It's an educational purpose.

Ohkay... seems pretty pointless to me. What kind of connection do you have avaliable to the Yun from your PC? WiFi? Ethernet? USB?

It's USB. to Serial pin. If it's better to use Ethernet, please guide me to a solution.

I would suggest using Ethernet or WiFi, then use scp (get Putty for Windows for that, or install one of the Linux subsystems) and scp the file over the network. Then you can access that file using Arduino code using the Bridge.h library and the FileSystem object.

See this, At the end of it they provide an example. But in our case, What would be our 'userid' and 'destination directory' ? We tried a similar approach with no success.
We've used the IP of the Yun (via Wi-Fi), In case of using Ethernet, What would be different ?

User ID is probably root. Destination directory? Whatever you want. /tmp is probably best.

Thanks, I'll try this at nearest time possible. I guess it's going to SD card directory So i don't need a command [at loop] to receive it. That's neat!

You can send a file, byte after byte, using Serial.
On the Arduino side, you parse serial communication and put bytes inside an array. At the end, you reconstruct the file.

What tool i can use to send that file from PC to Arduino ?

I think that not exist a tool like this. You should create this PC tool using, for example, Visual Studio.

Back in the mists of time (late 1990s, if anyone's counting), there existed a file transfer protocol called XMODEM that was used to send a file across a link normally used for a terminal, on small, publicly available systems known as Bulletin Board Systems, or BBSes.
XMODEM divided a file into packets of 129 bytes, sent and acknowledged one packet at a time. It had a simple 8-bit checksum to verify the file contents which was just "ok" over a reasonably reliable line, line and inadequate on a noisy one. But it was one of the first experimenter-built and widely used protocols.
As it was pushed harder and harder (larger file sizes, higher line speeds intolerant of the small, single-packet handshake) and its weaknesses became more problematic,a number of derivatives were developed to address the weaknesses.
ZMODEM was one of those, which allowed the sender a "sliding window" of packets, so it could keep sending packets (up to the window maximum) without stopping to wait for each acknowledgement, and could use larger packet sizes, among other improvements.
They are relatively easy to implement, XMODEM more-so, and source code or specs can be found by looking around.
If your files aren't horrendously large and the lines are fairly reliable, even XMODEM may be adequate.

The first question is what do you want to do with your image : Arduino Yun has a Linux chip & an Arduino chip.
And I don't think that image treatment must happen in the Arduino side...
So you can send your image with scp to Linux side, then do what you want with it and perhaps, eventually, send the result for action to the Arduino part.

I want to send an image, This image is to be attached to an email which would be sent to email address.

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


text:
How can I program an ESP 10 module
I buy an ESP-10 module and I want to upload custom room to its flash. The problem is that there is no way to access GPIO 0 pin! Is there some way around it to upload custom room without connecting GPIO 0 to the ground?
How in the earth should I program it without this pin?
here is an address to supplier's page which contains schematic and some other details.
https://www.tindie.com/products/George/esp8266-esp-10-module/#product-description

you can't. io 0 and io 2 are on this board connected and pulled up together

why are they connected? what is the purpose of this module?

for normal operation io 0 and io 2 must be pulled HIGH at startup. for flashing mode mode io 0 must be LOW and io 2 HIGH

You can't.  Not without physical modification to the PCB itself (remove the chip, scratch off a pad and trace, replace pad with fine enamelled copper wire tinned at the end, replace chip).  All you can use is whatever firmware is currently installed in the module.


text:
Will this sensor work with arduino?
I'm building an electronic gate. I'm needing a photoelectric sensor to detect cars. This one in the link looks decent. it runs on 12v so I will need to power it separately from the arduino. But does this mean it also puts 12v back to the signal wire? Will that work with ardunio without burning the circuit? How many V can i send into an arduino pin?
thanks
photo electric sensor

Some arduino boards use a 5v microcontroller, some use a 3.3v processor. The input voltage may not be above that. You have to use a few electronic components to fix it. It depends on the output of the detector, but two resistors to lower 12v to 5v is the most common solution. Search for: voltage divider arduino.

I'm not sure what I will end up with, but the one i have now is a arduino uno made by keyestudio. I'm not sure if it means anything but there is a 3.3 and a 5 v power supply from it. Sorry, i'm kinda new at this. but using resistors to drop the voltage does seem like a pretty good solution.

Edit your question to add the information that you're using the Keyestudio Uno. The question should contain all the necessary information rather than having to hunt through the comments for it.

The sensor you specified states:
Output: SPDT Relay Output

If accurate, it may be inferred that the output is simply 3 contacts where one is normally open and the other is normally closed and the 3rd is the common.  If true then you can treat the output as if it were an ordinary Single Poll Double Throw (SPDT) switch.  Note, with regard to processors, an ordinary switch may need to de-bounced.  This depends on how the state of the switch is used.

to my understanding that's basically it. there is a relay inside the sensor and hte sensor just sets off the relay. i should be able to run 5v to it and just listen for that 5v to go to pin2

When connected to 5V the input to the arduino should be 5V.  But what is the input when not connected?  When the relay is open?  Ah, this is where you need a pull down resistor.  So as not to allow the arduino's input to float to an unknown voltage.

yes possibly. the arduino is supposed to have that built in. maybe my off brand arduino doesn't. I had to build my own pull down. but the instructions were pretty clear. just grounding a resistor. When i get my hands on the sensor ill be able to tell if itl work or need the resistor.

Truth is, many embedded processors have the ability to program in a pull up or even a pull down resistor.  I didn't want to go that route as explaining the details requires more than what we do here in a stackexchange comment section.  In addition, these pull up / down resistors are usually weak by design and may not exist on all pins.  Finally, by using a SPDT switch that breaks before makes (most do) and making sure the wiring is correct (we don't want to short out the power supply!!) we can force the digital input both high and low w/o using a resistor.  But do double check the wiring!!


text:
threshold voltage level and blinking problem
I am using arduino pro mini 3.3 V,8 Mhz.vcc of the this arduino is coming from AC-DC converter with regulator 3.3 volt.I am listening analog data from voltage divider approximately 250 milivolts.
I want to basically,If analog voltage will reach 250 milivolts then led on.Otherwise led off.I am using avarage 100 ms for voltage data.
But,I have seen led on blinking for threshold voltage.Such as,The voltage level is changing 248-254.led on,led of,led on...I don't want to blink.
What can you do in such situations?Voltage level and slightly variable voltage?
Thanks

The internal reference of 1.1v might be better as reference. For the blinking at the threshold, add hysteresis to your sketch.

What is the sensetive ac voltage stabilization method coming from
  voltage divider and it contains noise filter capacitor and take
  avarage?

Calculating an average by using 3/4 of the current average and 1/4 of the new measurement (exponential average) works well for me in a lot of situations. You can adjust the constants as you see fit, as long as they add to 1.0. I use powers of 2 and shifting for maximum performance:
// Exp. average: 3/4 old avg + 1/4 new data, with rounding
int16_t xpavg(int16_t newdat, int16_t avg){

   // (3 * avg + 1 * newdat) / 4
   return( (((avg<<2) - avg + newdat) + 2) >> 2 );
}

As Jot mentioned in his comment you can write code to follow a hysteresis. This means, that the LED is only turned on, when the analog value is a bit above the threshold, and only turned off, when it's a bit below the threshold. You can see this behavior in Schmitt Triggers, which work that way (though they are getting the hysteresis via a corresponding electrical circuit, not through code). You wrote, your voltage readings are noisy in the range of about 10mV.
Depending on how your current code is structured, you can reach this goal by using if statements:
if( value > threshold + margin ){
    digitalWrite(LED_pin, HIGH);
} else if( value < threshold - margin ) {
    digitalWrite(LED_pin, LOW);
}

You can choose a good value for margin (this depends on the desired behavior). Start with a margin of 7mV (which should filter out the noise of 10mV) and change it, until it works as intended.

Thanks for answer.I want to ask twto question.
1)If margin coming slightly larger,what can be done?If we apply same think,the range will grow.
2)What is the sensetive ac voltage stabilization method coming from voltage divider and it contains noise filter capacitor and take avarage?I am searching software method?

Sorry, I don't understand your questions (seems, that english is not your native language). The margin would be a constant, which you choose depending on the noise of your analog signal and the desired behavior. You can even define 2 margins for turning on and off at different margins. And what do you mean with the voltage divider and capacitor? You wrote, that you have a signal, that is changing between 248mV and 254mV (noise). What I proposed is a software method.

I am sorry for grammar mistakes.If noise range of the voltage datas 248 mv-258mv then you are true.I can add margin to my code.But,such as If noise range of the voltage datas 190mv-300mv,What can i do?If I add to margin my code,it will be a waste of time for the switch threshold voltage level.Thanks.

If my proposal is too much of a compromise, you only can try to reduce the noise of your signal. Reducing noise in an analog signal can be a complex thing. You can add a low pass filter (combination of capacitor and resistor). You can try to isolate the electronics from the source of the noise (can be a running motor, a power line nearby, etc...). You can try to convert the pure analog signal to a differential signal for the distance from the source to the Arduinos pins (noise gets induced in both lines the same). Difficult to answer, without knowing more about the appliance.


text:
Data loging while browsing a menu on LCD shield
I'm new in arduino and not particularly awaken when it comes to code ;) .
I'm developing a device SD logging Temperatures from 2 thermocouple .
Hardware works well and I'm now trying to refine use of the LCD with a menu.
I want to be able to, while logging data on the SD card (lets say every second), browsing a menu to:

See current temperatures
see the max value from the measurements
see time already elapsed
etc.

I've used a menu code from (https://www.instructables.com/id/Arduino-Uno-Menu-Template/)
The thing is when I enter a sub-menu(menuItem()), while I'm not out of this sub menu the code is not looping anymore, so data logging would be paused.
So my question is: how should I organize my code to be able to do a repetitive task in background(logging temperatures) while browsing a menu giving information and/or proposing actions (Stop datalogging, reset etc).
Here is the code from instructables modified to be used with adafruit LCD shield:
/***************************************************************************************
    Name    : LCD Button Shield Menu
    Author  : Paul Siewert
    Created : June 14, 2016
    Last Modified: June 14, 2016
    Version : 1.0
    Notes   : This code is for use with an Arduino Uno and LCD/button shield. The
              intent is for anyone to use this program to give them a starting
              program with a fully functional menu with minimal modifications
              required by the user.
    License : This program is free software. You can redistribute it and/or modify
              it under the terms of the GNU General Public License as published by
              the Free Software Foundation, either version 3 of the License, or
              (at your option) any later version.
              This program is distributed in the hope that it will be useful,
              but WITHOUT ANY WARRANTY; without even the implied warranty of
              MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
              GNU General Public License for more details.
 ***************************************************************************************/
/*
   This program is designed to get you as close as possible to a finished menu for the standard Arduino Uno LCD/button shield. The only required modifications
   are to add as menu items to the master menu (menuItems array) and then modify/adjust the void functions below for each of those selections.
*/

// You can have up to 10 menu items in the menuItems[] array below without having to change the base programming at all. Name them however you'd like. Beyond 10 items, you will have to add additional "cases" in the switch/case
// section of the operateMainMenu() function below. You will also have to add additional void functions (i.e. menuItem11, menuItem12, etc.) to the program.
String menuItems[] = {"ITEM 1", "ITEM 2", "ITEM 3", "ITEM 4", "ITEM 5", "ITEM 6"};

// Navigation button variables
int readKey;

// Menu control variables
int menuPage = 0;
int maxMenuPages = round(((sizeof(menuItems) / sizeof(String)) / 2) + .5);
int cursorPosition = 0;

// Creates 3 custom characters for the menu display
byte downArrow[8] = {
  0b00100, //   *
  0b00100, //   *
  0b00100, //   *
  0b00100, //   *
  0b00100, //   *
  0b10101, // * * *
  0b01110, //  ***
  0b00100  //   *
};

byte upArrow[8] = {
  0b00100, //   *
  0b01110, //  ***
  0b10101, // * * *
  0b00100, //   *
  0b00100, //   *
  0b00100, //   *
  0b00100, //   *
  0b00100  //   *
};

byte menuCursor[8] = {
  B01000, //  *
  B00100, //   *
  B00010, //    *
  B00001, //     *
  B00010, //    *
  B00100, //   *
  B01000, //  *
  B00000  //
};

#include <Wire.h>
#include <LiquidCrystal.h>

// Setting the LCD shields pins
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>

Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {

  // Initializes serial communication
  Serial.begin(9600);

  // Initializes and clears the LCD screen
  lcd.begin(16, 2);
  lcd.clear();

  // Creates the byte for the 3 custom characters
  lcd.createChar(0, menuCursor);
  lcd.createChar(1, upArrow);
  lcd.createChar(2, downArrow);
}
//////////////////////////////////////////////
void loop() {
  mainMenuDraw();
  drawCursor();
  operateMainMenu();

  Serial.print("Loop");
}
///////////////////////////////////////////////
// This function will generate the 2 menu items that can fit on the screen. They will change as you scroll through your menu. Up and down arrows will indicate your current menu position.
void mainMenuDraw() {
  Serial.print(menuPage);
  lcd.clear();
  lcd.setCursor(1, 0);
  lcd.print(menuItems[menuPage]);
  lcd.setCursor(1, 1);
  lcd.print(menuItems[menuPage + 1]);
  if (menuPage == 0) {
    lcd.setCursor(15, 1);
    lcd.write(byte(2));
  } else if (menuPage > 0 and menuPage < maxMenuPages) {
    lcd.setCursor(15, 1);
    lcd.write(byte(2));
    lcd.setCursor(15, 0);
    lcd.write(byte(1));
  } else if (menuPage == maxMenuPages) {
    lcd.setCursor(15, 0);
    lcd.write(byte(1));
  }
}

// When called, this function will erase the current cursor and redraw it based on the cursorPosition and menuPage variables.
void drawCursor() {
  for (int x = 0; x < 2; x++) {     // Erases current cursor
    lcd.setCursor(0, x);
    lcd.print(" ");
  }

  // The menu is set up to be progressive (menuPage 0 = Item 1 & Item 2, menuPage 1 = Item 2 & Item 3, menuPage 2 = Item 3 & Item 4), so
  // in order to determine where the cursor should be you need to see if you are at an odd or even menu page and an odd or even cursor position.
  if (menuPage % 2 == 0) {
    if (cursorPosition % 2 == 0) {  // If the menu page is even and the cursor position is even that means the cursor should be on line 1
      lcd.setCursor(0, 0);
      lcd.write(byte(0));
    }
    if (cursorPosition % 2 != 0) {  // If the menu page is even and the cursor position is odd that means the cursor should be on line 2
      lcd.setCursor(0, 1);
      lcd.write(byte(0));
    }
  }
  if (menuPage % 2 != 0) {
    if (cursorPosition % 2 == 0) {  // If the menu page is odd and the cursor position is even that means the cursor should be on line 2
      lcd.setCursor(0, 1);
      lcd.write(byte(0));
    }
    if (cursorPosition % 2 != 0) {  // If the menu page is odd and the cursor position is odd that means the cursor should be on line 1
      lcd.setCursor(0, 0);
      lcd.write(byte(0));
    }
  }
}

void operateMainMenu() {
  int activeButton = 0;
  while (activeButton == 0) {
    int buttons;

    buttons = lcd.readButtons();

    switch (buttons) {
      case 0: // When button returns as 0 there is no action taken
        break;
      case 2:  // This case will execute if the "forward" button is pressed
        buttons = 0;
        switch (cursorPosition) { // The case that is selected here is dependent on which menu page you are on and where the cursor is.
          case 0:
            menuItem1();
            break;
          case 1:
            menuItem2();
            break;
          case 2:
            menuItem3();
            break;

        }
        activeButton = 2;
        mainMenuDraw();
        drawCursor();
        break;
      case 8:
        buttons = 0;
        if (menuPage == 0) {
          cursorPosition = cursorPosition - 1;
          cursorPosition = constrain(cursorPosition, 0, ((sizeof(menuItems) / sizeof(String)) - 1));
        }
        if (menuPage % 2 == 0 and cursorPosition % 2 == 0) {
          menuPage = menuPage - 1;
          menuPage = constrain(menuPage, 0, maxMenuPages);
        }

        if (menuPage % 2 != 0 and cursorPosition % 2 != 0) {
          menuPage = menuPage - 1;
          menuPage = constrain(menuPage, 0, maxMenuPages);
        }

        cursorPosition = cursorPosition - 1;
        cursorPosition = constrain(cursorPosition, 0, ((sizeof(menuItems) / sizeof(String)) - 1));

        mainMenuDraw();
        drawCursor();
        activeButton = 2;
        break;
      case 4:
        buttons = 0;
        if (menuPage % 2 == 0 and cursorPosition % 2 != 0) {
          menuPage = menuPage + 1;
          menuPage = constrain(menuPage, 0, maxMenuPages);
        }

        if (menuPage % 2 != 0 and cursorPosition % 2 == 0) {
          menuPage = menuPage + 1;
          menuPage = constrain(menuPage, 0, maxMenuPages);
        }

        cursorPosition = cursorPosition + 1;
        cursorPosition = constrain(cursorPosition, 0, ((sizeof(menuItems) / sizeof(String)) - 1));
        mainMenuDraw();
        drawCursor();
        activeButton = 2;
        break;
    }
  }
}

// If there are common usage instructions on more than 1 of your menu items you can call this function from the sub
// menus to make things a little more simplified. If you don't have common instructions or verbage on multiple menus
// I would just delete this void. You must also delete the drawInstructions()function calls from your sub menu functions.
void drawInstructions() {
  lcd.setCursor(0, 1); // Set cursor to the bottom line
  lcd.print("Use ");
  lcd.print(byte(1)); // Up arrow
  lcd.print("/");
  lcd.print(byte(2)); // Down arrow
  lcd.print(" buttons");
}

void menuItem1() { // Function executes when you select the 1st item from main menu
  int activeButton = 0;

  lcd.clear();
  lcd.setCursor(3, 0);
  lcd.print("Sub Menu 1");

  while (activeButton == 0) {
    int buttons;

    buttons = lcd.readButtons();
    switch (buttons) {
      case 16:  // This case will execute if the "back" button is pressed
        buttons = 0;
        activeButton = 1;
        break;
    }
  }
}

void menuItem2() { // Function executes when you select the 2nd item from main menu
  int activeButton = 0;

  lcd.clear();
  lcd.setCursor(3, 0);
  lcd.print("Sub Menu 2");

  while (activeButton == 0) {
    int buttons;

    buttons = lcd.readButtons();
    switch (buttons) {
      case 16:  // This case will execute if the "back" button is pressed
        buttons = 0;
        activeButton = 1;
        break;
    }
  }
}

void menuItem3() { // Function executes when you select the 3rd item from main menu
  int activeButton = 0;

  lcd.clear();
  lcd.setCursor(3, 0);
  lcd.print("Sub Menu 3");

  while (activeButton == 0) {
    int buttons;

    buttons = lcd.readButtons();
    switch (buttons) {
      case 16:  // This case will execute if the "back" button is pressed
        buttons = 0;
        activeButton = 1;
        break;
    }
    }
  }

I thank you for your help, and hope it will be helpful for others

The key is that the menu code must never wait as the operateMainMenu() function does. Instead, it has to test the buttons, do a required task, if any, quickly, and return. This means it depends on being called very frequently so it can respond to the buttons quickly, but also must return quickly when there is nothing to do. You make those calls from your loop() function, typically.
Look at the Arduino example, "BlinkWithoutDelay". In that example everything is decided by reading the time - millis(), where in your case, you'll be deciding by testing and reacting to the buttons. Just remember never to loop to wait for an input; just test for it once and act on it or just go away if it isn't there.
Your loop() function will do nothing but give each "worker" routine an opportunity to do something:
void loop(){
   menuRun();
   dataLogRun();
}

, for instance. Each of those functions gets a frequent opportunity to do one of its tasks - or not - and return, so the next one gets a chance. A loop like this one runs extremely frequently when there is nothing to do, meaning both the menu function and the data-logging function can be very responsive when something is needed.

Thanks for the answer! I didnt had the time to test but I understood the concept. I will get back at you if something is not working.

Sure - and let us know how it works out.

I've simplified the menu (no sub menu) and it is mostly working. Now I have problem regarding memory, the SD logging crash because of lack of memory(IDE warning when compiling). When  remove unnecessary code line (Serial. print), it succeed to open and write txt file, but when I try  to, read txt file in the serial monitor, it displays squares ?!! But regarding The logic of your answer, I get i and was able to apply it. Would it be interesting that I post my code?


text:
Use a button on LCD shield to pause the code
I'm creating a Temperature logging device with thermocouple K and SD card breakout and a RGB LCD Shield Kit w/ 16x2 Character Display (with buttons).
Everything runs ok: temperature displaying on the LCD and logging on txt file on the micro SD card work well
Now I try to configure button on the shield

button UP to reset measurements and timer , it works
button Down to pause measurements, then when pushed again, continue measurements. I don't know how to do that (how to go out the while condition).
 if (buttons) {

if (buttons & BUTTON_UP) {

  lcd.clear();
  lcd.print("RESET ");
  if (SD.exists("datalog.txt")) {

    SD.remove("datalog.txt");
    File dataFile = SD.open("datalog.txt", FILE_WRITE);
  }

  else {

    // open the file. note that only one file can be open at a time,
    // so you have to close this one before opening another.
    File dataFile = SD.open("datalog.txt", FILE_WRITE);
    // if the file is available, write to it:

  }
 StartTime = millis();

  delay(500);

}
if (buttons & BUTTON_DOWN) {
  lcd.clear();
  lcd.print("STOP");
  while (buttons & BUTTON_DOWN){

      ;
  }

}

I already thank you for your help,
Vincent

think about your first two if statements .... why are you testing buttons in the second if statement? .... you already tested it in the first if statement .... same with the last if statement ..... also, check the while (buttons & BUTTON_DOWN){ statement at the bottom ..... do you think that the values of buttons and BUTTON_DOWN will ever change? .... if you think that they will change, then what changes them?

This way of testing the buttons comes from the example given with the adafruit RGB LCD shield library. I tried not to re-test "buttons" in the IF statement after the first if(buttons) but the lcd diplays all statements of the next if(BUTTON_DIRECTION) like all the if test give a TRUE. Sorry it is difficult to be clear.

You are not saying much about how buttons is valorized or its data type, but assuming it is a numeric variable which gets somehow set by, let's say a readButtons() function, then consider the following snippet replacing your while-loop:
do {
  delay(10);
  // re-evaluate whatever sets the buttons variable
  buttons = readButtons();
while(!(buttons & BUTTON_DOWN));

The loop above will continue until the button down is pressed and it's a little resilient regarding contact bouncing, but not 100% reliable, so I assume the readButtons() performs also some debouncing.

Thank you Roberto, you have seen right. I'm using the LCD shield library, with a lcd.readButtons function.

@Vincent if this solves your problem then please accept the answer so that others will be able to use it as a reference


text:
Please answer this
what is the difference between transmitting and receiving leds(circled) connected to sensor board and ir emitter and receiver diode shown in second pic?Will the output change it i replace the former leds by latter?if yes then how?
Second pic is from https://www.amazon.in/CENTIoT-Universal-Infrared-Emission-Receiver/dp/B071NK3KD4/ref=sr_1_10?keywords=ir+leds&qid=1554913735&s=gateway&sr=8-10

Please don't re-post the same question

only one of those is a LED .... the other is most likely a photo-transistor

@sempaiscuba this is not same question, i think u did not get my question or maybe i didn't explain it clearly but still i got my answer.

The dark coated LED has a filter, that filters out other wavelengths except for the one, that it is specified for. The clear one doesn't have this coating, since it is used for sending. If you replace the coated one by an uncoated version, the results may get worse, when other IR sources are present (like the sun).
Also the specifications of the LEDs might be different, we can only speculate about that without knowing the part numbers of the used LEDs.
All in all it might not be a good idea to exchange the LEDs for one another. You haven't stated, why you want to do this.


text:
What is the difference between the two sensors?
I am working on a project which requires the use of sensors and i don't know which one to use so i would like to know the difference between the two.

They seem pretty similar. One uses surface-mount components and the other through-hole components. But my guess would be that they do pretty much the same thing. I'd prefer the first one, as it have some bypass capacitors on it, which could make it's signal a bit more stable.

It would be helpful if you would provide spec sheets or at least part numbers and sources for the 2 boards. Otherwise we have to do some guesswork from the images provided.

Apart from the obvious construction and component differences the two sensors seem totally equivalent from their look.
They seems to both be FC-51 modules: those are “line followers” meaning one diode (the clear one) emits infrared light and the other (the dark one) measure the amount of IR light reflected by the surface in front of them.
The potentiometer is there to determine the triggering level so that when powered you can have a LOW signal on the OUT pin when the threshold is reached.

How do you know, that the output signal is digital? Wouldn't it be also possible, that the output voltage may be analog and the potentiometer controls the gain? I don't know, how I should be able to tell from the pictures.

Because those sensors are quite common and called FC-51 https://codetipste.blogspot.com/2017/04/ir-sensor-arduino.html?m=1.

Not to mention I stated "they seem totally equivalent by their look": without further information that is my best guess...

Ah, ok. Good, that you included the part number (FC-51), so that we have a reference. +1

How can i find the positive and negative terminal of transmitter and receiver of sensor in first pic?@RobertoLoGiacco

Power it up and use a multimeter maybe?


text:
Bluetooth gamepad via Adafruit Feather M0 Bluefruit BLE
I'm trying to build a Bluetooth-enabled gamepad out of an old Playstation 1 controller, using an Adafruit Feather M0 Bluefruit BLE.
I've programmed the board as a Keyboard HID and everything works: the controller button presses trigger keyboard presses through the Feather. However, treating the controller as a keyboard means I get no analog joystick support.
The Feather M0 supports a Gamepad HID mode, but it's limited to 8 buttons and one joystick (but not analog), which is obviously not enough for a Playstation 1 controller.
I'm a bit stumped here: do I have any way of registering the BLE as a gamepad, to enable analog support, but with as many buttons as I need and two joysticks?
My code so far, on GitHub.

how does it matter, if the joystick is analog? you have a mcu with analog pins. read the joystick, convert the values and send them. or am I missing something here?

It seems that adafruits firmware doesn't support/implement that.

@Juraj he means there is only D-pad support. So only left right up down (on or off).

@Gerben, thank you for the explanation. it is not about analog. joystick is a different HID profile then gamepad

and the joystick HID profile is not supported over (nRF52?) BLE. (there are really two M0 ARM MCUs on this board?)

@Juraj, my issue is sending data over in the correct manner, not reading it from the pins. But still, since joystick HID is not supported over this chip, it seems like I'm out of luck.

@Gerben, that info seems to be for the EZ-Key, not the Feather M0.

Adafruit has the same AT firmware in all Bluefruits

@Juraj, argh, I see. I'll try to map it as the mouse then, if the Feather will let me send both keyboard and mouse data. Thanks for the help!


text:
Connect 20 12v led to an arduino mega
I want to control about 20 leds with an arduino mega.
This leds works with 12v voltage.
I tried to put 20 relays but this solution is not good for me because leds will often blink
I have also tried transistors but it needs to make a pcb.
I am looking for a solution without having to create a pcb
Any idea ?
Thanks

something like this perhaps?  https://i1.wp.com/media.boingboing.net/wp-content/uploads/2017/07/IMG_3397.jpg?fit=680%2C429&ssl=1

You need to be able to turn these LEDs on and off individually? If you only need to turn them all on or off as a group you could use a single transistor.

If you're using relays correctly then your LEDs should not blink. There are "digital" relay modules that are made to be driven from 5V CMOS logic, but 20 relays will take a lot of power. Transistors are a much better bet.

You can use the commonly available L298N module to drive four of your LEDs with each module. That means you would need five of them.

Those modules are suitable for driving either one stepper motor, two DC motors (in both directions), or four "unidirectional" loads such as your LEDs.
The input can be connected directly to your MEGA, but you may need additional series resistors depending on the LED you use (though this likely does not apply for LEDs specified as "12V").
There are also LED driver eval boards available which may suit your needs:
https://www.digikey.de/product-detail/de/adafruit-industries-llc/1455/1528-1019-ND/4990768

The ULN2803 is a chip with 8 darlington transistors in it designed for driving higher voltage, low-ish current, loads like this.  With 3 of them you have 24 channels to drive your LEDs.
You can get them on a breakout board quite easily, or as a DIP chip for working with breadboards.

This sounds like a good solution. A DIP package with 8 darlingtons on it should be able to handle 8 LEDs, and 3 DIP chips would fit on a pretty small breadboard or PCB. Transistors are better/easier to deal with than relays for modest current DC loads like this anyway.

Three TPIC6B595 shift registers, controlled by 3 pins from the Mega, can do this easily. Shift in 3 bytes with on/off state of the LEDs.
Can sink 150mA per output from 12V source.  The LEDs need current control, from simple resistor for 20mA loads, to a constant current driver per LED for higher current LEDs.
I used them to sink current from 12V for the LED strings in this display. The small digits needed ~ 20mA per segment, the larger digit is really 2 groups of 3 LEDs, drawing about 40mA per segment. One shift register per digit.
https://www.youtube.com/watch?v=6HZ0Mr51jUY

Try s MOS- FET transistor.  Its not expensive and easy to drive.  Can be directly connected to the Arduino.  Look for standard circuit diagrams.  1 P- Mos Fet and 1 Resistor per channel,  esch can drive several Amperes st 12V...

You don't need gate resistors for logic-level MOSFETs. They have capacitive inputs just like CMOS logic chips, and draw almost no input current.

Connecting up 20 single transistors would be really tedious, vs 3 chips.  I even made a board with a 328P, FTDI module, and 3 shift registers to drive 24 LEDs for  an hours/5 minute intervals clock display.  Very compact, about <25x50mm if I recall. Board with 4 shift registers to coontrol gates of 32 MOSFETs to drive larger loads with screw terminal connectors was much bigger, 100mm x100mm. And no microcontroller.


text:
Return constant string
Look at this code :
char * function1()
{
    return « hello »
}
Where is stored hello string ?
Is there a copy ?
What i want to avoid is to have a memory leak or accessing to another string instead of hello
Thanks

What language is this code written in? What is the point of asking a question about "code" without specifying the language?

It is arduino c

Arduino C does not support «» quotes. In Arduino C return statement must end in ;.

String literals in C and C++ are stored in static memory, which in case of Arduino platform is ordinary data memory.
If we overlook the typos, your code is essentially equivalent to
char *function1()
{
  static char literal[6] = { 'h', 'e', 'l', 'l', 'o', '\0' };
  return literal;
}

with a remark that in C and C++ you are not allowed to modify string literals. (Some nuances also depend on the specific language - C vs. C++ - which you failed to specify). Regardless of the language, it is always a better idea to use const char * pointers (as opposed to char *) to point to string literals.
There's no dynamic memory allocation here, and therefore no memory leaks possible. What you mean by "accessing another string" is not clear.

const char* function1() { return "hello"; }

Where is stored hello string ? Is there a copy ?

The string is compiled into the program memory. Before setup() is called the constant values are copied to the data memory (aka SRAM).
The function will return the pointer to the same string (memory location).
To save data memory the string literal can be access directly in program memory.
__FlashStringHelper* function1() { return F("hello"); }

Cheers!
Ref.

https://en.cppreference.com/w/cpp/language/string_literal
https://www.nongnu.org/avr-libc/user-manual/pgmspace.html

Thanks but i do not understand. Should i use flashstringhelper and F() to make it work. It does not matter to me where the string is stored. I just want to read it from calling function

The first variant works nicely but will consume data memory. To avoid this the second variant can be used but it will require using special access functions. Please see the references.


text:
Arduino Strings concatenation
I am working on an arduino mega 2560 sketch.
I have to parse http query strings.
My program is concatenating strings for each http request.
And i have an http request every second during all day.
I have read that this kind of work may cause ram memory fragmentation. I am very upset about this because my program will randomly crash if there are no free ram memory.
Do you know if there is a way to initialise a string with a given memory length ?
I do not want to work with char arrays because i need indexof, substring functions and comparison with ==
Thanks

And how many of those concatenated requests do you expect to fit into the memory???

What is wrong with using the char* functions provided by C? They can do everything a String can, without the problem of memory fragmentation, and if you need a function that does not exist, it's very easy to find an implementation or create it yourself.

There is a way to initialize an Arduino String with a given memory length: see reserve() method. It will generally greatly reduce or entirely eliminate memory fragmentation, if you can afford reserving a sufficient amount of memory in advance.
Just keep in mind that this is a "soft" boundary: once your string gets longer than the reserved amount, String will quietly resume reallocating memory with all those typical consequences.
It is not clear what you plan to do if the pre-reserved amount of memory proves to be insufficient. Fall back to "memory fragmentation"? Anything more elaborate than that will be pretty much as complex as performing manual management of a char[] array.
All the functionalities you requested are present for char[] arrays as well, might just require a few more lines of code. And it is not clear why one might "need" comparisons to be == specifically.
This might also be an XY problem. Why are you trying to concatenate all these requests in memory? What are you planning to do with them once you are done "concatenating"?


text:
Generate 1khz square signal with Arduino Mega
I want to generate a 1khz square signal with an Arduino Mega.
I have read the MCU contains several timers.
What i want to do is to configure one of this timers.
My first question is: Is there a way to automatically control an output pin from the timer, without having to execute any line of code in my arduino program ? Look at my code: i need to write a line in ISR(TIMER1_OVF_vect). Some MCU can do that but i did not find any information about it on documentation. (Some pins are connected on timer outputs, by hardware conception).
My second question is: What is wrong on my calculation on my code ?
I want 1khz and i get 990Hz
Here is what i've done:

Arduino Mega runs at 16Mhz = 16000Khz
I have set a /8 prescaler, so timer's frequency is 8000Khz
The frequency should by divide by two because i have 2 states (HIGH and LOW): 4000Khz
The interupt is fired when the counter reach 65536. So if i load 65536-1000 in TCNT1, the timer should count 1000 times in order to fire the interupt. So my frequency is 4000khz/1000 = 1khz.

What is wrong ?
Thanks a lot
void setup() {
  pinMode(14,OUTPUT);

  noInterrupts();
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 65536 - 1000;
  TCCR1B |= (1 << CS11);    // Prescaler clock / 8
  TIMSK1 |= (1 << TOIE1);
  interrupts();
}

ISR(TIMER1_OVF_vect)
{
  TCNT1 = 65536 - 1000;
  digitalWrite(14, digitalRead(14) ^ 1);
}

void loop() {

}

This does not really answer your question, but actually there really is a way to let the timer automatically control an output pin. You can use the timer in output compare mode. You write a value in the corresponding OCR (the register) and let the timer run from 0 to this value. When reaching that, the corresponding pin gets automatically toggled and the timer resets. That way you can do this a lot more accurate

You shouldn't set TCNT1, but you need to set the TOP value. This depends on which PWM/timer mode you use (see table in datasheet). I know it's ICR1 or OCR1A on the UNO. Not sure about the Mega.

As explained in the previous answer, you forgot to account for the time
taken by the CPU to handle the interrupt prologue. As a general rule, if
you want consistent timing, you should never reset the timer by
software after the initialization.
If you want to run the timer in normal mode, and use it to schedule
interrupts at a period that is not the timer's own period, it is
possible, but you should not use the overflow interrupt for this
purpose. You should instead use any of the “compare match” interrupts,
and adjust the compare register in the IRS in order to schedule the next
interrupt. For example:
void setup() {
    pinMode(14,OUTPUT);

    TCCR1A = 0;            // normal mode
    TCCR1B = _BV(CS11);    // clock @ F_CPU/8
    TCNT1  = 0;            // clear timer
    OCR1A  = 1000;         // first COMPA match in 1000 cycles
    TIFR1  = _BV(OCF1A);   // clear interrupt flag
    TIMSK1 = _BV(OCIE1A);  // enable TIMER1_COMPA interrupt
}

ISR(TIMER1_COMPA_vect) {
    OCR1A += 1000;      // schedule next interrupt
    PINJ   = _BV(PJ1);  // toggle PJ1 = digital 14
}

Note that the line OCR1A += 1000; can cause a wrap around, but this is
no problem, as the addition wraps around in exactly the same way as the
timer itself.
The advantage of this technique is that you can schedule up to three
different tasks, having different periods, with only one timer. And you
can even schedule tasks in a non-periodic fashion.
That being said, if you do not need the timer for anything else other
than scheduling a single periodic task (or up to four tasks sharing the
same period), then a better solution is to let the timer handle the
period all by itself. Configure the timer in mode 12 or 14 (CTC or fast
PWM, with TOP = ICR1), and set the period with ICR1 = 999;. Then the
ISR is reduced to:
ISR(TIMER1_COMPA_vect) { PINJ = _BV(PJ1); }

and you save a few cycles. This would be my preferred solution if I
absolutely had to output the signal on pin 14.
Note that this solution should give you the right average frequency,
but you will still have some jitter, because the interrupt can
occasionally be delayed by other interrupts. If you are free to choose
the output pin, then the best solution is to let the timer handle the
PWM generation all by itself. Set the timer to any PWM mode (fast PWM is
the simplest) and use one of the waveform generators in order to
generate the PWM signal. Only the PWM-capable pins (those marked with a
“~” symbol) can be used this way. For example, Timer 1 can output to
pins 11 (OC1A), 12 (OC1B) and 13 (OC1C).
Edit answering the question:

what is the goal of TIFR1 = _BV(OCF1A); // clear interrupt flag?

Whenever the timer value matches the contents of the compare register
OCR1A, the interrupt flag OCF1A (Output Compare Flag of timer 1,
channel A) is raised. This flag controls the interrupt request when the
OCIE1A bit (Output Compare Interrupt Enable 1A) is set. The flag is
automatically cleared when the ISR runs, and can be manually cleared by
writing a logic 1 to it (yes, it is kind of backwards).
It is quite likely that the flag raises early in the start process,
while the Arduino library is initializing. If the flag is up when you
enable the interrupt, an interrupt request is immediately triggered. In
order to avoid that, the common practice is to clear the flag before
enabling the interrupt.

Thanks but what is the goal of "TIFR1  = _BV(OCF1A);   // clear interrupt flag" ?

pin 14 is an example, i can do it on any pin

@Bob5421: See amended answer.

About your answer on "TIFR1 = _BV(OCF1A)": Is it necessary if i put noInterrupts() / interrupts() in my setup function ? Thanks a lot

@Bob5421: Yes. noInterrupts() does not prevent the interrupt request from being triggered. The interrupt would then fire as soon as you call interrupts().

That OCR1A  = -1000; is interesting -- why the negative?  Wouldn't it be equivalent to OCR1A = 65536 -1000; or First COMPA match in 64536 cycles?

@DaveX: OCR1A  = -1000; is indeed equivalent to OCR1A = 65536-1000;. That was an error of mine. I was mixing this up with the idea that TCNT1 = -1000; ensures the overflow fires in 1000 cycles.

My first question is: Is there a way to automatically control an output pin from the timer, without having to execute any line of code in my arduino program ?

Yes. It's called PWM with a 50% duty cycle.
You need to read up on 19. Output Compare Modulator (OCM1C0A) in the datasheet.

My second question is: What is wrong on my calculation on my code ? I want 1khz and i get 990Hz

You have to take into account the number of CPU cycles it takes to start executing your ISR. There's a short bit of code before your code is run that preserves any used registers on the stack and allocates any room needed for local variables. That takes time, and must be calculated into your timing factor.

The 19. Output Compare Modulator (OCM1C0A) feature seems like overkill for a 1KHz square wave.  That modulates timer 1 and timer 2 together based on OCR1C OCR0A and puts an output on B7.  An unmodulated 1kHz square wave could be done without overhead by using Timer 1 in one of the WGM modes with TOP as ICR1 or OCR1A.


text:
Reading Digital Pins and Outputing on entire Ports
I'm very new to coding so please don't grill me.
I'm working on a scientific project where I am using a NI-DAQ to digitally trigger mosfets to trigger 300us - 3ms pulses on two high powered LED arrays. My intention is to use the Arduino UNO to basically relay one digital output into many. It remains important to use the NI-DAQ as the pulses are dependent on video cues and other outputs, otherwise the pulses would be purely produced by the Arduino.
I have decided to the port Port reg output to accomplish this as it would appear to have the greatest temporal precision but I’m having a very difficult time getting a single pin to trigger a port. I would greatly appreciate some help.
My code currently looks as such:
int inpin = 2; //input specified as pin 2
int x = 0; // variable to store the read value

void setup() {
pinMode(inpin, INPUT); //sets digital pin 13 as input
DDRD=B11111111; //pin 8-13 is in output mode
DDRC=B11111111; //pin A0-5 designated output
}

void loop() {
x = digitalRead(inpin); //read the input pin
if (inpin = HIGH) PORTB=B11111111; // if digital input is high, all Bport high
if (inpin = HIGH) PORTC=B11111111; // if digital input is high, all Cport is high
if (inpin != HIGH) PORTB=B00000000; // if digital input is low, all Bport is low
if (inpin != HIGH) PORTC=B00000000; // if digital input is low, all Cport is low

}

At the moment it seems the board it reading the input but is not relaying the outputs correctly with the PORTB continuously off and PORTC continuously on. Any help would be great!

If your purpose is to just repeat an input why not take an IC meant for the task, They are commonly reffered to as buffers.

Check the Arduino pinout. It would seem you mixed up ports B and D.

Thank you Edgar, I fixed my typo in the set up area. Now both B & C are illuminated continuously.

I agree with ratchet. If you just want to repeat a digital input then use a buffer ship. Those respond in single-digit nanoseconds, with no programming needed. Arduino chips are relatively slow.

You have some coding errors.  You likely meant to write something like:
void loop() {
  x = digitalRead(inpin); //read the input pin
  if (x == HIGH) PORTB=B11111111; // if digital input is high, all Bport high
  if (x == HIGH) PORTC=B11111111; // if digital input is high, all Cport is high
  if (x != HIGH) PORTB=B00000000; // if digital input is low, all Bport is low
  if (x != HIGH) PORTC=B00000000; // if digital input is low, all Cport is low
}

Which could be simplified to:
void loop() {
if (digitalRead(inpin) == HIGH)
{
  PORTB=B11111111; // if digital input is high, all Bport high
  PORTC=B11111111; // if digital input is high, all Cport is high
}
else
{
  PORTB=B00000000; // if digital input is low, all Bport is low
  PORTC=B00000000; // if digital input is low, all Cport is low
}
}

Amazing! Thank you, I had been stuggling with that for some time. I thought an else statement would be apropriate I just didn't know how! Cheers

If you are doing this sort of low-level port manipulation, I suggest you
ditch the Arduino core and go the avr-libc way:
#include <avr/io.h>

int main(void)
{
    DDRB = 0xff;  // all port B as output
    DDRC = 0xff;  // all port C as output
    DDRD = 0;     // all port D as input
    for (;;) {
        if (bit_is_set(PIND, PD2)) {  // if PD2 reads HIGH
            PORTB = 0xff;  // all port B goes HIGH
            PORTC = 0xff;  // same for port C
        } else {
            PORTB = 0;     // all port B gos LOW
            PORTC = 0;     // same for port C
        }
    }
}

This compiles to very efficient code that takes at most 7 CPU
cycles per loop iteration. In contrast, a call to digitalRead() can
take hundreds of cycles, greatly increasing the program latency.
Obviously a buffer would still be way better in terms of latency, as
pointed out by ratchet freak in a comment.

I'll explore this option too. Although latency is important In my project it is most important that each pin within a port in in sync with the rest of the pins within the same port. I believe this approach, similar to the buffer approach, will be sufficient. Thank you


text:
Why does using ESP8266 in deep sleep mode still drain the battery quickly?
I've made a "weather station" using the ESP8622. To save battery I'm using sleep mode but still the battery is drained after a couple of days. According to this post it should last at least a year.
I haven't done any measurements yet, wanted to know if there's something obvious that I've missed that could explain why the battery is drained so quickly? Attaching code and an image showing the hardware setup.
#include "DHT.h"
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#define DHTPIN D2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

const char* ssid     = "xxxx";
const char* password = "xxxx";

const char* host = "xxxx";

void setup() {
  Serial.begin(115200);
  dht.begin();
  delay(10);

  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  readSensorsAndPost();
  ESP.deepSleep(18e8); //30 minutes
}

void readSensorsAndPost() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  char charVal[10];
  dtostrf(t, 5, 2, charVal);
  makeAnHttpRequest(charVal);
}

bool makeAnHttpRequest(String msg) {
  //send the value
}

void loop() {

}

First do measurments

The example shows a Sparkfun Thing, which the article notes doesn't have extra peripherals. What you show is something different, like a NodeMCU dev board, which typically has a linear regulator, possibly a power LED (which the article notes can be removed).
I see you're using a DHT11 or DHT22, which has a pull-up resistor. The pull-up resistor is constantly using power. Instead of connecting the pull-up to the power rail, you can connect it to a GPIO pin and pull that pin LOW before you go into sleep, which effectively disables the sensor and stops it from drawing power just to keep the data line high.
Safe to say that somewhere there is something drawing power -- have you measured the actual current draw in deep-sleep, or are you only noting that your batteries run low sooner than expected?

I haven't done any measurements yet but when I have I will post the result. Will also change the setup as per your suggestion.

You are also powering the USB interface chip, which never goes to sleep.

@Majenko is there an easy way to disable powering the USB interface chip?

Migrate to a standalone module without all the extra junk and use an external USB adapter.


text:
Is it possible to combine a HC-05 Bluetooth module and a shrinked arduino ATtiny45/85 to control a motor, LEDs, or other components?
I'm thinking of making a tiny RC toy project that is controlled through Bluetooth with most components at its tiniest size. I'm a complete beginner in this area so i'm not completely familiar with lots of components so please don't mind me if i sound dumb and uneducated. Anyway...
If it's possible: how many components can i use with the ATtiny45/85? or should i go with the atmega8.
I have a m20 mini motor, a micro servo and a few leds. This doesn't include other components that i havent purchase such as dc driver module and HC-05 Bluetooth module.
If not possible: what other options I can do to create my project.

The ATTiny has 5 usable pins (6 if you decide to reuse the Reset pin). Since it doesn't have UART hardware, you need to use a SoftwareSerial library to communicate with the HC-05. This takes 2 pins. To drive a motor, you need at least 1 pin. If you need to control it's speed (instead of just on and off), you would need to generate a PWM signal. Either through hardware timer or by code. (The ATTiny has 2 timers. When you want to use PWM with hardware timer, you need to make sure, that the SoftwareSerial library doesn't want to use the same timer). For the servo it's similar. The servos position is encoded by pulse lengths. (Make sure, that the used library doesn't want to use an already used timer)
Unless you use techniques as multiplexing or matrixes (which are not that useful for a small number of LEDs), you need 1 pin per LED.
Depending on what exactly you want to achieve, you will pretty fast run out of pins. Since you are a beginner you should start with a chip with more pins. If you don't know, how exactly your project will be in the end, better by a chip with maybe double the pins, that you think you need. Develop, until you really know, what functionality your project should have, what not and what you need to achieve that. Based on this you can choose the correct chip, that is as small as possible. Also consider using SMD parts in the finished version. There are mostly much smaller, but also more difficult to solder.

Thank you for your answer :) i understand most of the information you mention in the first part but i've never counter information about using chips as shrink arduino. Can you inform me more about that topic?

An ATTiny is a chip (more precise a microcontroller), but not an Arduino. Mostly an Arduino is a complete board with the microcontroller and every other essentiell part, that is needed for operation. If you use the internal oscillator of the microcontroller, you can operate it nearly without extra components, though you should add a decoupling capacitor.

I see thank you I learnt alot from it. So i looked around and found the ATtiny2313 that is relatively quite a good size and contain lots of pins. Can i get your opinion on this chip. Will it be good for my project?

That looks good. It has a hardware UART, so that you don't need SoftwareSerial, also 4 PWM outputs with 2 timers and more pins. I think with this you should be able to create your project. For the LEDs: If you only want to control them between on and off, you can also use shift registers to expand on the pins. Finally, when you are finished developing the project, you can change the chip to a smaller one, that is right enough for it (too much limitation during development can be frustrating and expensive).

Thank you for your guidance, with these information I can learn more on electronics and start on my project :)


text:
Arduino Modbus - Rtu slave with Raspberry pi using MAX-485
I am trying to use Arduino as Modbus- RTU slave and Raspberry Pi as a Modbus master
I have interfaced Max485 (RS485 to TTL converter) with Arduino and Rs485 to USB converter in Raspberry Pi, Initially, I was able to send data from Arduino to Raspberry Pi, but the data seems to inconsistent and fails to read most times
I am using https://github.com/smarmengol/Modbus-Master-Slave-for-Arduino for Arduino
Minimal Modbus for raspberry pi
Connections:
DI(max485)- TX ( Arduino),
DE(max485) -D4 ( Arduino),
RE(max485) - D4( Arduino),
Ro(max485) - RX( Arduino),
Vcc(max485) -5v( Arduino),
Gnd (max485)- GND( Arduino)
code for Arduino
#include <ModbusRtu.h>
uint16_t au16data[6] = {};
Modbus slave(5,0,4);
void setup() {
  slave.begin(19200,SERIAL_8N1 );
 }
void loop() {
  au16data[0]=100;
  au16data[1]=200;
  au16data[2]=300;
  au16data[3]=400;
  au16data[4]=500;
  au16data[5]=600;
  slave.poll( au16data, 6 );
  delay(3000);
}

python code
import minimalmodbus
from datetime import datetime
import time

instrument = minimalmodbus.Instrument('/dev/ttyUSB0', 5)
instrument.serial.baudrate = 19200
instrument.serial.bytesize = 8
instrument.serial.parity = minimalmodbus.serial.PARITY_NONE
instrument.serial.stopbits = 1
instrument.serial.timeout =5
instrument.mode = minimalmodbus.MODE_RTU

while(1):
    try:
        val = instrument.read_registers(0,6)
        # Registernumber, number of decimals
        print val
    except IOError:
        error_msg = "Failed to read from device"
        error_time = datetime.now()
        print "IO Error Time",error_time.isoformat(),error_msg

    except ValueError:
        error_msg = "Failed to read CRC"
        error_time = datetime.now()
        print "Value Error Time",error_time.isoformat(),error_msg
    time.sleep(2)

Sounds like a hardware problem. Show the schematic, and an oscilloscope trace.


text:
Sending data from Arduino Mega to nodeMCU using serial (Multiple sensor data) & upload to firebase
Im working in a project where i have to deal with multiple sensor data.

BME 280
WindSpeed Sensor
Water level Sensor x 10
Soil moisture x 5
Soil pH sensor x 2

i have found this code for both arduino uno and nodemcu esp8266
//Arduino code
#include <SoftwareSerial.h>
SoftwareSerial s(5,6);

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

void loop() {
int data=50;
if(s.available()>0)
{
 s.write(data);
}
}

//for nodeMCU
#include <SoftwareSerial.h>
SoftwareSerial s(D6,D5);
int data;
void setup() {
s.begin(9600);
Serial.begin(9600);
}

void loop() {
  s.write("s");
  if (s.available()>0)
  {
    data=s.read();
    Serial.println(data);
  }
}

In this code here send 1 value from arduino uno to nodeMCU...
but if i want to send 10 values(float temperature,humidity,pressure,waterlevel,windSpeed,windDirection) from mega to nodeMCU using serial, how to do that using serail.

As i know nodemcu still not  work as a slave device . Maybe this support will be available in the future but if you test it and it work . This how to do it
Let's assume you have tow dat to send cast them to string , concatenated characters of string_data1+string_data2 then send theme via uart communication to the nodemcu .
Now in the nodemcu take the string and decoding  [split] string to string 1 and string 2 and cast theme again to any var type you want.
If this method seems so hard to you or your level in coding is still under development use some library exist that can do the work for you i recommend. The easytransfer library by madsci1016 in github enter link description here.


text:
Problem with String& argument of a function
I am trying to send SMSs using a GSM module with Arduino Mega. I have followed a tutorial and downloaded the SIM908IDE100 library. I am using the function
SendSMS(String&, const char [27]);.
It works fine when I type:
sms.SendSMS("1234567890","Text message");
where "1234567890" is the telephone number I want to send the SMS to and "Text message" is the text of the SMS.
If I instead try to pass to the function a String containing the telephone number
String number = "1234567890";
sms.SendSMS(number,"Text message");
I get the following error:
exit status 1
no matching function for call to 'SMSGSM::SendSMS(String&, const char [27]);'
I don't understand what String followed by an ampersand means. What am I supposed to pass the function as its first argument?

are you sure it is not the sms.SendSMS("1234567890","Text message"); giving you "no matching function"?

@Juraj Yes I am sure. The sms.SendSMS("1234567890","Text message");  works fine and the SMS is sent without any problem.

Hint: Try sms.SendSMS(String("1234567890"),"Text message");

The function prototype in sms.h is
char SendSMS(char *number_str, char *message_str);

if number is String, you should have
sms.SendSMS((char*) number.c_str(),"Text message");

c_str() is a function of the Strinng class. It returns a pointer to internal char array of the String object.
The cast to char* is necessary because the author of the library didn't make the parameter constant with const char*. (It is a good practice, to declare pointers and references as constants.)
The error message no matching function for call to 'SMSGSM::SendSMS(String&, const char [27]); shows the arguments you try to use. String& is reference to some instance of the String type

if I use sms.SendSMS(number.c_str(),"Text message");    I get the error: no matching function for call to 'SendSMS(const char*, const char [13])'

sms.SendSMS((char*) number.c_str(),"Text message");

thank you very much, it works now. I still don't fully understand how (char*) works, would you mind to briefly explain it? thanks again

https://www.tutorialspoint.com/cprogramming/c_strings.htm


text:
Control motor DC with buttons
i'm new user with Arduino, i want to know if there is a tutorial to control the rotation of a motor like : with 4 buttons, the first to rotate +pi/2 the second to rotate -pi/2 the third to rotate +-pi and the fourth to stop the rotation
thanks a lot !!

there may be such a tutorial, but you do not need it ..... what you are referring to is not one programming action, it is two actions ..... one is the detection of button presses ..... the other is motor rotation control ..... find tutorials that teach you how to read button presses and how to control the motor .... then you put those two together so that the program does what you want it to do

Is the motor a stepper? If not you will have trouble getting it to position reliably.

duncan Thank you for your reply :) ! I do not know yet about the type of engine to choose, I want to run a table with a motor connected to the Arduino board. I think to do it on a stepper motor as you say

jsotola, thanks for you reply :) , i'll try, i know how works the detection of button presses, i'm learning about rotation control


text:
Class help - Same Object types seem to mix values with each other
I'm having issues with two objects of the same class type. I have a LED class, which has functions to fade in and out, a LED. In my code, I create two objects of this class, and on the board, I fade them in and out.
Code is in my FadingLED.h file, which I #include.
I instantiate these classes - and then in my setup(), I call an Init function on the classes to initialise them and pass all the parameters I need.
And then in the loop, I just keep calling an Update method, which internally, uses Millis() to handle updating the brightness of the LED.
But I think I am having cross contamination of the objects. Because if I trigger them both to fadein and out at the same time, only the first LED fades. If I stagger them, the 2nd LED works, but it's timing seems to be out. It seems like maybe I'm somehow mixing member variables within the class. I'm new to this, so it's probably an obvious fault?
My calling code:
// This #include statement was automatically added by the Particle IDE.
#include "Buzzer.h"
#include "FadingLED.h"

// Pins being used by devices.
int LED1_PIN = A4;
int LED2_PIN = A5;
int PIR_PIN = 3;
int BUZZER_PIN = 0;

// Instantiate the objects
FadingLED LED_1;
FadingLED LED_2;
Buzzer buzzer;

// Setup global variables.
bool AllStill = true;

// Setup.
void setup() {
    // Initialise the two LEDs
    LED_1.Init(LED1_PIN, 500, 0, true);
    LED_2.Init(LED2_PIN, 500, 250, true);
    // Set the PIR pinmode.
    pinMode(PIR_PIN, INPUT);
    Particle.publish("Device","Board initialised", PUBLIC);
    buzzer.Beep(100, 2200);
}

// Function to check if movement has been detected.
bool CheckMovement() {
    // Read the pin value.
    int val = digitalRead(PIR_PIN);

    // Has a new movement been detected?
    if(val==true && AllStill==true) {
        buzzer.Beep(200, 2200);
        AllStill = false;
        Particle.publish("Device", "Movement Detected", PUBLIC);
    }
    AllStill = !val; // All still is false if we have movement.

    return val != 0;
}

void loop() {
    // Check for moment.
    bool val = CheckMovement();
    // Update connected devices.
    LED_1.Update(val);
    LED_2.Update(val);
    buzzer.Update();
}

And then the class it's self.
/*
 * A class that manages a fading LED. This needs to be on PWM pin.
 */
class FadingLED {
  int             delayedStart = 0;               // Period to wait before starting.
  int             ledPin = -1;                    // The pin to control - Note, as we're fading, we must use an ANALOG pin.
  long            fadePeriod = 0;                 // The time to do a full light and dim cycle.
  unsigned long   previousMillis = 0;             // The previous millis value.
  bool            debug = false;                  // Should we output stuff?
  float           fadeChangeGap = 0;              // Calculated gap between brightness changes.
  unsigned long   firstMillis = -1;

public:
  void Init(int LedPin, int FadePeriod, int DelayedStart, bool Debug) {
    ledPin = LedPin;
    fadePeriod = FadePeriod;
    delayedStart = DelayedStart;
    debug = Debug;
    pinMode(ledPin, OUTPUT);
    Particle.publish("Debug", "LED Initialised on " + String(ledPin) + ", Fade Period is " + String(fadePeriod) + ", Start Delay is " +  String(delayedStart), PUBLIC);
  }

  void Update(bool isOn) {

      // Get the current millis since the board was started.
      unsigned long currentMillis = millis();

      // Is this the first time this code is running?
      if(firstMillis == -1)
        firstMillis = currentMillis; // Set the first time this class was run.

      // Adjust the current time to be based on the current time since the object was created.
      currentMillis = currentMillis - firstMillis;

      // Calculate the difference bwteen the last update and now.
      unsigned long diff = currentMillis - previousMillis;

      int brightness = 0;

      // Check if we have a delay set. If so, don't light up yet.
      if(delayedStart > 0 && currentMillis < delayedStart) {
        Particle.publish("LED", "In Delay Start...", PUBLIC);
         previousMillis = currentMillis;
        return;
      }

      // Map the difference which is betweem 0 and the cycle time, to a value between 0 and 512.
      // Map the difference, which is between 0 and the fade period, to a value between 0 at 512.
      int b = map(diff, 0, fadePeriod, 0, 512); // 512, as we'll brighten to 256, then then fade from 256 to 512.

      // Check if we should be bringtning, or fading...
      if(b > 255) {
        brightness = 255 - (b-255);
      }
      else
      {
        brightness = b;
      }

      if(isOn == false) {
        brightness = 0;
      }
      // Set the brightness.
      analogWrite(ledPin, brightness);

      // And then save the timestamp.
      if(currentMillis - previousMillis >= fadePeriod) {
         previousMillis = currentMillis;
      }
  }
};

Is there an error with how I am defining the class (I'd expect to use the 'new' keyword, but don't). Maybe in the class it's self, there is a way to say the field are private to that object only?
If I try:
FadingLED LED_1 = new FadingLED();

I get:

conversion from 'FadingLED*' to non-scalar type 'FadingLED' requested

Any assistance or advice would be great.

Keep it simple, keep it straightforward, don't try to do "smart" things that have consequences. You assign -1 to a unsigned long, that's no good. You compare -1 to a unsigned long, that's can't be right either. Avoiding the rollover problem is good, but introducing another similar problem by using -1 as a flag is not good. This: "currentMillis < delayedStart" is not good, even if it is only used after power on, it still causes a problem during the rollover. You need a clear and logical structured code in the update function. Think first what you want to do before writing down code.

The keyword 'new' is not needed, it would allocate it dynamically (which you don't need). In that case the statement should be FadingLED* LED_1 = new FadingLED(); Thus LED_1 would be a pointer.

Also you don't need to compare booleans against false or true, you can use if (bool_x) or  ir (!bool_x).

A4 and A5 don't work with analogWrite https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

I combined the FadingLED class with your "calling code" sketch, then removed the references to libraries that I don't have. The first error I received was regarding the seven lines of code immediately under the "class FadingLED {" line.
My answer will only address the issues with the way the class is written. As Jot and Michel Keijzers have mentioned in their comments to your question, there may be other issues that need to be fixed.
The following sketch uses a slightly modified version of the FadingLED class. There are 2 constructors. One is a "no argument" constructor, and the other accepts 4 arguments. Both constructors call the private function initStuff() to initialize other variables, pinModes, etc.
/*
 * A class that manages a fading LED. This needs to be on PWM pin.
 */
class FadingLED {

  private:

    int             delayedStart;     // Period to wait before starting.
    int             ledPin;           // The pin to control - Note, as we're fading, we must use an ANALOG pin.
    long            fadePeriod;       // The time to do a full light and dim cycle.
    unsigned long   previousMillis;   // The previous millis value.
    bool            debug;            // Should we output stuff?
    float           fadeChangeGap;    // Calculated gap between brightness changes.
    unsigned long   firstMillis;

    void initStuff(){
      previousMillis = 0;
      fadeChangeGap = 0;
      firstMillis = -1;
      pinMode(ledPin, OUTPUT);
      //Particle.publish("Debug", "LED Initialised on " + String(ledPin) + ", Fade Period is " + String(fadePeriod) + ", Start Delay is " +  String(delayedStart), PUBLIC);
    }

  public:

    FadingLED(): delayedStart(0), ledPin(-1), fadePeriod(0), debug(false){
      initStuff();
    }

    FadingLED(int LedPin, int FadePeriod, int DelayedStart, bool Debug):
      delayedStart(DelayedStart),
      ledPin(LedPin),
      fadePeriod(FadePeriod),
      debug(Debug){
      initStuff();
    }

    void Update(bool isOn) {

        // Get the current millis since the board was started.
        unsigned long currentMillis = millis();

        // Is this the first time this code is running?
        if(firstMillis == -1)
          firstMillis = currentMillis; // Set the first time this class was run.

        // Adjust the current time to be based on the current time since the object was created.
        currentMillis = currentMillis - firstMillis;

        // Calculate the difference bwteen the last update and now.
        unsigned long diff = currentMillis - previousMillis;

        int brightness = 0;

        // Check if we have a delay set. If so, don't light up yet.
        if(delayedStart > 0 && currentMillis < delayedStart) {
          //Particle.publish("LED", "In Delay Start...", PUBLIC);
          previousMillis = currentMillis;
          return;
        }

        // Map the difference which is betweem 0 and the cycle time, to a value between 0 and 512.
        // Map the difference, which is between 0 and the fade period, to a value between 0 at 512.
        int b = map(diff, 0, fadePeriod, 0, 512); // 512, as we'll brighten to 256, then then fade from 256 to 512.

        // Check if we should be bringtning, or fading...
        if(b > 255) {
          brightness = 255 - (b-255);
        }
        else
        {
          brightness = b;
        }

        if(isOn == false) {
          brightness = 0;
        }
        // Set the brightness.
        analogWrite(ledPin, brightness);

        // And then save the timestamp.
        if(currentMillis - previousMillis >= fadePeriod) {
           previousMillis = currentMillis;
        }
    }
};

// This #include statement was automatically added by the Particle IDE.
//#include "Buzzer.h"
//#include "FadingLED.h"

// Pins being used by devices.
int LED1_PIN = A4;
int LED2_PIN = A5;
int PIR_PIN = 3;
int BUZZER_PIN = 0;

// Instantiate the objects
FadingLED LED_1(LED1_PIN, 500, 0, true);
FadingLED LED_2(LED2_PIN, 500, 250, true);
//Buzzer buzzer;

// Setup global variables.
bool AllStill = true;

// Setup.
void setup() {
    // Set the PIR pinmode.
    pinMode(PIR_PIN, INPUT);
    //Particle.publish("Device","Board initialised", PUBLIC);
    //buzzer.Beep(100, 2200);
}

// Function to check if movement has been detected.
bool CheckMovement() {
    // Read the pin value.
    int val = digitalRead(PIR_PIN);

    // Has a new movement been detected?
    if(val==true && AllStill==true) {
        //buzzer.Beep(200, 2200);
        AllStill = false;
        //Particle.publish("Device", "Movement Detected", PUBLIC);
    }
    AllStill = !val; // All still is false if we have movement.

    return val != 0;
}

void loop() {
    // Check for moment.
    bool val = CheckMovement();
    // Update connected devices.
    LED_1.Update(val);
    LED_2.Update(val);
    //buzzer.Update();
}


text:
Why are my thermistor readings backward?
I'm trying to build a thermistor that will flash an LED when the temperature is above 30 C. My set-up appeared to be reporting the room temperature correctly to the Serial Monitor, but then I noticed that exposing the thermistor to a hot object causes the reported temperature to drop, whereas exposing it to a cold object causes the reported temperature to rise.
I'd built a simpler thermistor circuit earlier with a similar approach and everything seemed to function correctly. I'm not sure what I broke here:
const int WarningLED = 7;
const int Thermistor = 0;

/* Thermistor information:
 * P/N: BC2301-ND
 * MFG P/n: NTCLE100E3103JB0
 * DESC: THERMISTOR NTC 10KOHM 3977K BEAD, IDX: 1 */

int Vo; // voltage between thermistor and R1
float R1 = 10000; //10 KOHM resistor used for voltage divider
float TR; // resistance of negative temperature coefficient (NTC) thermistor
float beta;  //beta will later equal ln( TR / Rref )
float Tk, Tc, Tf;

/* Steinhart-Hart equation coefficients via data table at
 * http://www.vishay.com/docs/29049/ntcle100.pdf
 * Bead used: 3977K (refer to #9 values on Nominal R table) */
float A = 3.354016e-03,B = 2.569850e-04;
float C = 2.620131e-06,D = 6.383091e-08;

void setup() {
  pinMode(WarningLED, OUTPUT); //sets the warning LED pin as a digital output
  Serial.begin(9600);          //  setup a serial port to enable comms with the computer.
 }

void loop() {

  Vo = analogRead(Thermistor);
  Serial.print("Vo: ");
  Serial.print(Vo);
  Serial.println(" mV");

  //Voltage divider equation: R2 = R1 * [Vo / (Vi - Vo)]
  //where R2 = TR, Vi = 1023.0 :
  TR = R1 * ((float)Vo / (1023.0 - (float)Vo));
  Serial.print("Thermistor resistance: ");
  Serial.print(TR);
  Serial.println(" ohms");

  beta = log(TR/10000); // As per extended Steinhart-Hart equation,
  //  where Rref = 10,000 (refer to page 10 of the PDF linked above)
  Tk = (1.0 / (A + B*beta + C*beta*beta + D*beta*beta*beta));
  Tc = Tk - 273.15;
  Tf = (Tc * 9.0)/ 5.0 + 32.0;

  Serial.print("Temperature: ");
  Serial.print(Tk);
  Serial.print(" K; ");
  Serial.print(Tf);
  Serial.print(" F; ");
  Serial.print(Tc);
  Serial.println(" C");
  Serial.println();

  if (Tc > 30.0) digitalWrite(WarningLED, HIGH);
  else if (Tc < 30.0) digitalWrite(WarningLED, LOW);
  delay(1000);
}

On the Serial Monitor, this reports:
Vo: 550 mV
Thermistor resistance: 11627.91 ohms
Temperature: 294.74 K; 70.86 F; 21.59 C

Exposing this to a warmer temperature incorrectly reports:
Vo: 597 mV
Thermistor resistance: 14014.08 ohms
Temperature: 290.61 K; 63.43 F; 17.46 C

I notice that, among other issues, this is reporting increased resistance in the thermistor despite that I'm using an NTC, but I'm not sure why this is occurring.
Notable parts used in this circuit:

Thermistor: NTCLE100E3103JB0
R1: 10 KOHM
R2: 1 KOHM
C1 & C2: 33 nf

The voltage Vo is not the voltage over the thermistor, it is the voltage over R1! Switch the place of the thermistor and R1.
/Mikael

I re-derived the equation for the thermistor resistance after taking into account my mistaken voltage divider placement, which flipped the Vo and Vi parts of the equation so that instead the equation is TR = R1 [ (Vi - Vo) / Vo]. This resolved the issue; thanks! Moreover, it's useful seeing that thermistor values running the wrong way can indicate that voltage division has been taken from the wrong location!

In addition, note that the Vo is definitely not expressed in mV (millivolts), but in ADC steps , i.e. 1024th of the Vref, that is here 5V (default). And the reference is there that it should be 512 for 25deg.
Also, don't be fooled with the precision of the numbers given. Tolerance is 2% to 5% on the R25 value, which means up to ~25 "steps" (Vo). Assuming that reversing the R1 and TR gives you 450 at 22 deg, it means that your real threshold of 30 deg could be anywhere between 28 and 32 (roughly).
You can get better results by calibrating your TR: at 25deg, measuring its real resistance and using that instead of 10000 in your calculation is a first option. Calibrating for other temperatures is already way more complicated.


text:
Using 18650 batteries with a 3.7v to 5v boost converter
I'm looking to set up a 1-meter strip of WS2812B LEDs (60 LEDs) with an off-the-shelf RF LED controller with a remote. The LEDs want a 5V supply - I've tried running them off 3.7v but the colour accuracy goes out the window and they start flickering and doing all sorts of other nonsense.
To work around that I'm considering using a DC boost converter like one of these pololu ones. I'll wire up a couple 18650 batteries in parallel to supply the voltage and my plan is to hook them up to the LEDs via the boost converter.
Idiot question time: is it safe to wire the boost converter directly to the output terminals of the battery/batteries and take the 5V off the +5v pin using a common ground? Or am I doing something dumb?
Also, I'm not 100% sure how to go about charging this setup. One option would be to put the batteries in cases and use an external charger with replaceable cells.
Would it make more sense to get one of these? This should be able to handle both charging AND stepping up the voltage, am I right?

How many LEDs are you going to be using?

Interesting question, but it's off topic.  Try Electrical Engineering SE

is it safe to wire the boost converter directly to the output terminals of the battery/batteries and take the 5V off the +5v pin using a common ground?

Yes. That is the normal way of using them.

Also, I'm not 100% sure how to go about charging this setup. One option would be to put the batteries in cases and use an external charger with replaceable cells.

That is the simplest option, yes. You shouldn't charge Li-Poly / Li-Ion batteries whilst using them - the load messes with the charge termination detection and can cause your batteries to over-charge and explode.

Would it make more sense to get one of these? This should be able to handle both charging AND stepping up the voltage, am I right?

That gets around the problem of charging while running, yes. A proper charger like that should bypass the battery when charging so the load is running from the incoming charge power rather than the battery.
One option you haven't considered though is to not use step-up.  Step-up is harder to manage with heavy loads. As you can see that first step-up module you link to has an upper limit of only 1.2A.  If you have 60 LEDs per meter, and 1 meter of LED strip, that's a maximum of 3.6A (60 * 0.02 * 3) which is 3x what that module can provide.
A better solution would be to use two batteries in series, not parallel, to give you about 7.2V. Then you can use a step-down switching regulator to give you your 5V and have far higher current limits.  Looking for a "UBEC" or "SBEC" in a model RC supplier shop is usually a good bet. For example:

Turnigy 5A (8-26v) SBEC for Lipo

HobbyKing™ HKU5 5V/5A UBEC

These are all designed for use with two or more LiPoly batteries in series.

Great answer. (Voted.)

Would those work with Li-ion batteries as well? Li-poly batteries are a bit wide for what I'm looking to do - the cylindrical form factor of the 18650 batteries feels like a better option.
I like the idea of using a step-down regulator - I hadn't considered that! Thank you!.

@poolski Yes, for all intents and purposes Li-Poly and Li-Ion are interchangeable. The main difference is the binding used to contain the battery components which gives the different shape.

@Majenko How would charging be handled with a step-down regulator? Those both look like they're just for regulating power, not charging. Would I need to build a charging circuit in or use removable cells?

Would wiring in something like this deal with the charge control and making sure that the circuit is powered from the right source while charging, do you think?
Edit: that seems like it has the same problem - it can't output more than 1A :(

You would typically use removable batteries with a UBEC


text:
How to assign two or more variables incoming from app
I'm really new to Arduino and have some doubts about how Arduino reads data. Lets suppose I have 3 variables a,b,c. I need these variables in my Arduino to make whatever. Since all variables are read using Serial.read() how can I distinguish between them in my Arduino?
Example:
Variable a: 2
Variable b: 3
Variable c: 4
Arduino example code:
void loop() {
int a = Serial.read();
int b = Serial.read();
int c = Serial.read();

if(a == '0'){
digitalWrite(yellowLed, HIGH);
}

if(b == '0'){
digitalWrite(blueLed, HIGH);
}

if(c == '0'){
digitalWrite(redLed, HIGH);
}

In every loop, my Arduino does serial.read() 3 times, if I only send value b from my app, since int a = Serial.read() executes first, will my b value be assigned to a? If yes, how can I avoid that problem and force the correct assignment? Aditionally, in every loop, if Serial.read() doesnt read anything, will my values be changed to null or zero?

https://majenko.co.uk/blog/reading-serial-arduino

didn't you ask a very similar question recently - https://arduino.stackexchange.com/questions/59976/how-can-i-distinguish-values-sent-from-arduino

This is a classic problem that is solved either by uniquely identifying each value or by agreeing on a pre-defined sequence of data.  However, it can be said that many solutions exist for this problem & that these are only 2 examples.
In the first case, the sender and receiver need to agree that all data will be sent in pairs.  A pair of bytes, for example, where the first identifies the data and the second is the data.  In this case the order of data does not matter.  And much more of one type of data can be sent than another.  This is good to use when the data rate is irregular and does not need to be fast.  Stock prices for example.
In the second case, the sender and receiver need to agree that all data will be sent in the same sequence even if there is no data to be sent.  Such a scheme may employ a special synchronizing bit to identify the beginning of a sequence of data.  Usually, when there is no data to be sent, a zero is sent.  But if zeros are significant, then special null characters will have to be agreed upon.  This is good when the data rate is regular and needs to be fast.  Digitized audio for example.

I think I will use the first option. But I have another doubt, since in every loop my variables try to read from Serial, if Serial is empty, will their value be changed to 0? if I use Serial.avalaible() in an if statement, will I get rid of that problem?

The Serial.available() tests if there is new data.  Use it to tell if there is no data and skip reading data for this iteration.


text:
How can I distinguish values sent from Arduino
Having in my visual basic app something like:
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        *whatever* value = serialPort1.Read*whatever*();
    }

Suppose my Arduino sends in every loop, the value read by a photoresistor. Suppose my Arduino also sends a 0 if certain led is LOW or a 1 if certain led is HIGH. Finally suppose my Arduino also sends a value that is equal to the number of times the loop has been executed.
In the 25th execution, lets suppose my Arduino sends something like:
Serial.write(LED_state) // 0 or 1 for LOW or HIGH
Serial.write(photoresistor_value) //lets suppose 25
Serial.write(loop_number) //25

Question: if all the values are sent using Serial.write or Serial.print, and all values are ints, how can I distinguish in my app if the value 25 received belongs to the photoresistor or to the loop? Is there any way to send something like (key, value) from Arduino so I can distinguish between the ints received so I can assign them correctly to my app variables?

Is there any way to send something like (key, value)

Sure:
Serial.print("LED state: ");
Serial.println(LED_state);

You will have to modify your VB code to parse that.