text:
Configuring the registers of i2c AD converter ADS122C04
I am not able to set the configuration registers of the TI´s converter chip ADS122C04 using arduino MEGA via I2C.
The code mainly consists of the following:
1-reset the chip (one byte)
2-choose register (WREG) and set register data (figure 59 of the data sheet) for all four registers
3- start conversion (one byte)
In sum, ten (10) bytes are sent in one i2c frame using an array of bytes as follows:
  //--------------------------------------------------------------------

int ADR_THeiz_Austritt = 0x40;                                  //hex Adress of the device

byte InitArray[10] = {6, 64, 54, 68, 10, 72, 5, 76, 112, 8};    //configuration array

 Wire.beginTransmission(ADR_THeiz_Austritt);            //  talk to Slave

 Wire.write(InitArray,10);             // bytes array is sent to slave on ACK handshaking

  status = Wire.endTransmission();     //status as in
                              //https://www.arduino.cc/en/Reference/WireEndTransmission

  Serial.print("Status Initialisierung = ");

  Serial.println(status);

//--------------------------------------------------------------------
status is a byte, which indicates the status of the transmission:
0:success
1:data too long to fit in transmit buffer
2:received NACK on transmit of address
3:received NACK on transmit of data
4:other error
after configuration, when reading the value of e.g. register 0, the result was 0 (default) !!
A second attempt was performed with a for loop
     //--------------------------------------------------------------------

      for (int i=0; i<10; i++)

  {

    Wire.beginTransmission(ADR_THeiz_Austritt);

    Wire.write(InitArray[i]);

    //delay(10);

  status = Wire.endTransmission();

  Serial.print("status Initialisierung ");

  Serial.print(i);                      //print the array element no

      Serial.println(status);          //print the status of transmision

      }

  //--------------------------------------------------------------------

the print function outputs the following: 00, 10, 23, 30,43,50,63,70,83,90 which means:
i=0, InitArray[i]=6, status =0 --> Reset of chip successfull
i=1, InitArray[i]=64, status =0 --> adressing Register 0 successfull
i=2, InitArray[i]=54, status =3 -->  value for Register 0 not transmitted !! (the same applies for all registers)
i=9, InitArray[i]=8, status =0 --> start chip successfull
My question: why am I not able to put a value in the registers? what am I doing wrong?
would appreciate your support!


text:
Using an ESP8266 with an Arduino Uno - can't get AT command to work
I am trying to connect an ESP8266 to my Arduino Uno.

Connections:
RX -> RX
TX -> TX
CH_PD -> 3.3v (Arduino 5v using voltage regulator)
VCC -> 3.3v
GND -> GND

I am running the RX and TX pins through a logic converter, dropping those down to 3.3v. Also, I have read that normally RX goes to TX and vice versa, but since I am trying to communicate with the chip using my computer (not the arduino) it needs to be the other way around.
I can't get the AT command to work on any baud rate. I was paying attention mostly to 9600, 115200, and 57600...I checked some others but it seemed like from reading these are the most common.
I used a multimeter to check the voltage of the RX/TX pins and after the logic converter my meter says it is outputting 3.2 volts (is this two low for serial to work?) Is their some +/- in the reading and it is actually 3.3v?

How do I go about troubleshooting this? Is it possible the AT firmware isn't loaded onto my chip? (I purchased it new, and recently).
UPDATE:
I'm reading about my logic level converter here, and I'm wondering if I have it setup right. My converter is labeled with HV -> HV4 and LV -> LV4 (you can see in the below picture). I'm wondering about where it says:
The middle section of the board is where the reference supply for your high and low voltages should go. Supplying voltage to all four of these pins is required. If you’re converting 3.3V to 5V (and vice-versa), for example, you’d run 5V into the “HV” side, and 3.3V into the “LV” input. Make sure each is grounded too!
So I need to provide power ("reference" power)? Some diagrams I have seen do this but I wasn't sure why:

UPDATE
I provided the reference supply and it up'd my voltage reading from 3.2 to 3.27 (I can assume it has enough voltage now?). I still can't connect with AT - on one of the baud rates I was getting stuff like !? as output.
UPDATE
I changed what pins were being used by RX/TX on my logic level converter, and now when I type AT on baud 115200, it outputs AT. Below is what it looks like for this configuration:

Do the soldered connections look good on the logic level converter?

Try loading the ESP8266-01/12F firmware once more from the Espressif and see if it's working correctly. Hope you know how to change to firmware/programing mode?
(GPIO 0->ground)->rest->burn program->GPIO0->high->power reset)

After writing such a long question, hopefully this is useful to someone else: After changing the logic converter channels (not sure why the first two weren't working) I was receiving AT as output - the only thing I needed to do after that was change No line ending to Both NL & CR and I am receiving AT OK now.

source: Stack Exchange

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

sort: votes


text:
digitalRead not reading input pin of ESP8266-01
I am trying to use a on-off switch with the ESP8266 to change whether GPI02 is HIGH or LOW. I am using GPIO3 as input. My circuit looks like this:

The red area to the right is a relay, I wasn't sure how to make it work in fritzing but I am sure that it is wired correctly, it just has a signal, +, and -, pin. The more important stuff is happening with the ESP8266. First, here is the code:
/*
  This a simple example of the aREST Library for the ESP8266 WiFi chip.
  This example illustrate the cloud part of aREST that makes the board accessible from anywhere
  See the README file for more details.

  Written in 2015 by Marco Schwartz under a GPL license.
*/

// Import required libraries
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <aREST.h>

// Clients
WiFiClient espClient;
PubSubClient client(espClient);

// Create aREST instance
aREST rest = aREST(client);

// Unique ID to identify the device for cloud.arest.io
char* device_id = "ew1zard";

// WiFi parameters
const char* ssid = "MaisonBlanche";
const char* password = "7932gLBw";

// Functions
void callback(char* topic, byte* payload, unsigned int length);

void setup(void)
{
  // Set input / output pin
  pinMode(3, INPUT);
  pinMode(2, OUTPUT);
  //pinMode(2, OUTPUT);
  //digitalWrite(3, 0);

  // Start Serial
  Serial.begin(115200);

  // Set callback
  client.setCallback(callback);

  // Give name & ID to the device (ID should be 6 characters long)
  rest.set_id(device_id);
  rest.set_name("esp8266");

  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Set output topic
  char* out_topic = rest.get_topic();
}

void loop() {

  // Connect to the cloud
  rest.handle(client);

  int read3 = digitalRead(3);
  Serial.println(read3 + " input");
  digitalWrite(2, read3);

}

// Handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {

  Serial.println("request from interwebs");
  rest.handle_callback(client, topic, payload, length);

}

The output of the Serial.println is always input (there is no HIGH or LOW or 1 or 0, or whatever it should be, before the input. I have verified that the switch is working. In the on position it is sending 3.3v to GPIO3 (I have measured it with my multimeter) and still the input never changes. In the off position it sends 0v and the ESP8266 just acts as if there is nothing to read it seems. Since I am using this with aREST and you can set the mode of pins through that, I thought maybe I had to set the pinMode with the aREST request cloud.arest.io/xxxxx/mode/3/i and it verifies with a JSON response that the pin is being set to input, but still no reading. Do I not have the ESP8266 wired correctly for this? Maybe I need some pull-ups/pull downs or I can't use the pins in the configuration I am using them? One other thing, when I set the input pin with aREST, it turns on the relay (sending something through GPIO2 for some reason). If I don't set the input with aREST the relay stays off.
UPDATE
I tried with this code to rule out that it might be aREST:
void setup() {
  // put your setup code here, to run once:
  pinMode(3, INPUT);
  pinMode(2, OUTPUT);

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

void loop() {
  // put your main code here, to run repeatedly:
  int read3 = digitalRead(3);
  Serial.print(read3);
  Serial.println(" input");
  digitalWrite(2, read3);
}

It always outputs 0 input, the ESP8266 seems to be ignoring that input pin.
UPDATE
I am now trying with GPIO0 as input. I have the switch wired to ground, and it leads to GPIO0. When I turn it on, GPIO0 reads 1 (on), then I use the switch and it turns the relay off correctly, then I try and turn it on again, and nothing happens, GPIO0 continues to be read at 0. So I can't use the switch past the initial off.

The expression read3 + " input" performs pointer arithmetic, i.e. you either add 0 or 1 to the start adress of " input", so you get either " input" or "input". Does the leading space disappear when pressing the button?
To correct your code you can print the number separately:
Serial.print(read3);
Serial.println(" input");

You should get rid of the rest and pub-sub code. You can add this later after having solved the problem with the button.
Also note that GPIO03 uses the same pin as RX. The docs state the following:
Serial uses UART0, which is mapped to pins GPIO1 (TX) and GPIO3 (RX).

So it should work after disabling Serial and after providing a pull down resistor. The resistor is needed to prevent having a floating input.

Comments are not for extended discussion; this conversation has been moved to chat.

The issue occurs when you try to use the RX port (3) and you also define Serial.begin. This is double dipping. You can only use the RX/TX as a single unit of digital or serial communication.

There are certain pins that output a 3.3V signal when the ESP8266 boots. This may be problematic if you have relays or other peripherals connected to those GPIOs. The following GPIOs output a HIGH
signal on boot: GPIO1, GPIO3, GPIO9, GPIO10. GPIO3:  pin must high at BOOT and is pulled up to that position. I have no idea what will happen if low at that point.  Since I2C I/O modules are cheep I use them and do not worry about the rest of the pins. Not the cheapest but keeps me out of trouble. It makes my life a bit easier as well as I pull up the I2C lines to the 3.3V and connect the PCF8574 to 5 Volts. No problem as the SCL and SCI are by definition Open Drain or Open Collector (Bipolar parts). This made my first try with a LCSD work first shot. I tried the 3.3V and it would not work.

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

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


text:
Arduino - fuse setting problem on ATmega328P-PU
I am trying to do fuse setting on ATmega328P-PU chips using an avr programmer.
I was successfully able to do fuse setting on 3 ATmega328P-PU chips (which I bought from one of the sites - I forgot). So I bought three more from Amazon.
When I execute avrdude -c usbasp -p m328p on the previous 3 chips, I got this response, and was able to do fuse setting.

avrdude: warning: cannot set sck period. please check for usbasp firmware update.
  avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.00s
avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: safemode: Fuses OK (E:FF, H:D9, L:E2)
avrdude done.  Thank you.

But when I execute the same command on the 3 chips I recently bought, I am getting this.
avrdude -c usbasp -p m328p

avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
     Double check connections and try again, or use -F to override
     this check.

avrdude done.  Thank you.

I triple-checked the wiring and soldering area. They all look fine.
Is this because the 3 chips I recently bought have a bootloader?
The description for the chip that works is here.

These chips have been configured for a 16 MHz external oscillator. Are you providing an external clock source on your board?

No. there is no external clock on the board.

The chips configured with a bootloader would also have the fuses set for an external clock (the factory default is the on-chip oscillator). Without an external clock they won't work.
I have a sketch that uploads files that also can provide an external clock for this eventuality.
As mentioned on that page an 8 MHz clock is provided on pin D8 of the programming board, so you can connect to D8 on the Uno which you are running the sketch on to pin 9 on the actual Atmega328P chip.
Alternatively find a 16 MHz crystal or resonator and connect that between pins 9 and 10 of your Atmega328P which will provide the clock that it is expecting. If you use a crystal you should also run 22 pF capacitors between each leg and ground, like in this image:


text:
Sending Multiple Information from BNO055 IMU to BridgeClient on Yun
I have an Arduino Yun which is interfaces via I2C to a Adafruit BNO055 breakout board.
My Aim is to use Python Flask in conjunction with BridgeServer and BridgeClient to obtain the Sensor Information from the ATmega32u4 microcontroller to the Microprocessor and use HTML5 Server Side Event (SSE) to display live sensor information on Network interfaces.
I would like to show the Euler angles and Linear Acceleration values:

heading
pitch
roll
linear_accerlation_x
linear_acceleration_y
linear_acceleration_z

An Example of similar concept can be obtained from Smart Measuring Cup by Adafruit. However, in the code sketch the user sends only one value :
BridgeClient client;
....
client.println(volume, 5);

And at the Python Flask end the code opens up a socket and uses makefile() method to read value
def yunserver_sse():
    try:
        # Connect to YunServer instance that's listening on localhost.
        soc = socket.create_connection(('localhost', 5678))
        socfile = soc.makefile()
        while True:
            # Get data from server.
            line = socfile.readline()
            # Stop if the server closed the connection.
            if not line:
                raise StopIteration
            # Send the data to the web page in the server sent event format.
            yield 'data: {0}\n\n'.format(line)
            # Sleep so the CPU isn't consumed by this thread.
            time.sleep(0)
    except socket.error:
        # Error connecting to socket. Raise StopIteration to quit.
raise StopIteration

Instead of sending just one measured parameter how can I send all above mentioned 6 at the same time?
note
I tried using ArduinoJson library but I find it difficult to parse the JSON on the Python Flask end as readline() expects a \n at the end of the string.

Apparently the solution to my problem was a simple client.println() after my JSON was ready to be printed to the BridgeClient.
Snippet:
root.printTo(client); client.println();

where root is DynamicJsonBuffer from the ArduinoJson library. The client.println() would immediately print \n and this would be read by the readline() python code.


text:
Quaternion values from BNO055 not available
I am trying to obtain Quaternion values from a BNO055 connected to ESP32-PoE board by Olimex.
Code
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>

Adafruit_BNO055 bno = Adafruit_BNO055(55);

void setup() {
  // put your setup code here, to run once:
  Wire.begin(13, 16, 400000);
  Serial.begin(115200);

  if (!bno.begin()) {
    Serial.println("No BNO055 Detected!");
    while(1);
  }
  delay(100);
  bno.setMode(Adafruit_BNO055::OPERATION_MODE_NDOF_FMC_OFF);
  bno.setExtCrystalUse(true);
}

void loop() {
  // put your main code here, to run repeatedly:
  imu::Quaternion quat = bno.getQuat();
  imu::Vector<3> euler = quat.toEuler();

  Serial.print("W: ");
  Serial.print(quat.w());
  Serial.print(F(" "));

  Serial.print("x: ");
  Serial.print(quat.x());
  Serial.print(F(" "));

  Serial.print("y: ");
  Serial.print(quat.y());
  Serial.print(F(" "));

  Serial.print("z: ");
  Serial.print(quat.z());
  Serial.print(F(" "));

  Serial.print("X: ");
  Serial.print((float)euler.x());
  Serial.print(F(" "));
  Serial.print("Y: ");
  Serial.print((float)euler.y());
  Serial.print(F(" "));
  Serial.print("Z: ");
  Serial.print(float(euler.z()));
  Serial.print(F(" "));
  Serial.println("");
  delay(200);
}

output
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00
W: 0.00 x: 0.00 y: 0.00 z: 0.00 X: 0.00 Y: nan Z: 0.00

The sensor seems to be working since I tried a simple script and the values are avaiable.
Is there some specific setting missing during setup() in order to obtain Quaternions.
Purpose
For Absolute orientation, the Quaternion values need to be converted to Euler .

why setExtCrystalUse? has the module an external crystal?

I think it is for I2C clock. It is set to true in most applications.

Apparently in the setup() it is preferable to have a delay(1000) as opposed to delay(100).
Code
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>
#include <math.h>

#define DEG (180/M_PI)

Adafruit_BNO055 bno = Adafruit_BNO055(55);

void setup() {
  // put your setup code here, to run once:
  Wire.begin(13, 16, 400000);
  Serial.begin(115200);

  if (!bno.begin()) {
    Serial.println("No BNO055 Detected!");
    while(1);
  }
  delay(1000);
  bno.setMode(Adafruit_BNO055::OPERATION_MODE_NDOF_FMC_OFF);
  bno.setExtCrystalUse(true);
}

void loop() {
  // put your main code here, to run repeatedly:
  imu::Quaternion quat = bno.getQuat();
  imu::Vector<3> euler = quat.toEuler();

//  Serial.print("W: ");
//  Serial.print(quat.w());
//  Serial.print(F(" "));
//
//  Serial.print("x: ");
//  Serial.print(quat.x());
//  Serial.print(F(" "));
//
//  Serial.print("y: ");
//  Serial.print(quat.y());
//  Serial.print(F(" "));
//
//  Serial.print("z: ");
//  Serial.print(quat.z());
//  Serial.print(F(" "));

  Serial.print("Yaw: ");
  Serial.print(euler[0] * DEG);
  Serial.print(F(" "));
  Serial.print("Pitch: ");
  Serial.print(euler[1] * DEG);
  Serial.print(F(" "));
  Serial.print("Roll: ");
  Serial.print(euler[2] * DEG);
  Serial.print(F(" "));
  Serial.println("");
  delay(200);
}

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


text:
Arduino board is turning off when I connect to +5V
I am trying to set up an LCD screen without using a resistor or a potentiometer for an Arduino project. This is the LCD I am using: Basic 20x4 Character LCD.
But when I connect to +5V on the Arduino board, my Arduino board turns off. This is how I have the LCD connected to the Arduino on a breadboard.

Connections:
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
Data:
• LCD D4 pin to digital pin 5
• LCD D5 pin to digital pin 4
• LCD D6 pin to digital pin 3
• LCD D7 pin to digital pin 2
LCD R/W pin to ground
LCD VSS pin to ground
LCD Cathode pin to ground
LCD Anode pin to digital pin 9
LCD VCC pin to 5V
Code:
// include the library code:
include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  analogWrite(6,20);
  // set up the LCD's number of columns and rows:
  lcd.begin(20, 4);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

Anode pin always connects with 5V... See my answer diagram. It will helpful.

Try out this connection. It will helpful.

Looking at your picture, it seems that you're powering everything through a USB cable. USB 1.x and 2.0 can supply up to to 500 mA AFTER the port is enumerated, otherwise the current is limited to 100 mA.
A quick current consumption budget:

LED backlight of your LCD module: typ 240 mA
Arduino Mega2560: min 70 mA
MIDI shield: some 15-35 mA

That's just 325-350 mA to begin with, and probably higher than that. It's still safely within the 500 mA limit, but as I said some computers will provide 500 mA only after successful enumeration of the device connected to the USB port.
My recommendation for you would be to power your Arduino + MIDI shield + LCD through a wall adapter > 7V. If it works, then the problem is your USB port being unable to supply the required current right from the start.

Alright ill try that out. it my not be visible  but i also have an Mp3 shield between  the Midi shield and arduino

Well, that will add some current consumption as well. You might be already above 500 mA! Under that load, the USB port of the computer shuts himself off for protection.

i think i found the issue one of the pins on the LCD might have been causing a short when i connected to 5v pin .i fixed it and it seems to be working. i did this with the shields on the arduino removed. i will add them back on and see if it works. if it dose not i know the issue is related to the power consumption of the USB. thanks for your help


text:
Restart sequence of NeoPixel stick with a push button at any time
I am really happy with my new Arduino stuff and playing around with all those pixels :).
I am new to programming and it's difficult to understand it, but with every success, I grow in knowledge.
My latest problem now is to restart my loop of incrementing the strip at any time with the push of a button.
I know that delay(); will stop the code completely and wait till the time passes, but I wrote some code without the use of delay(); and used millis(); instead.
So far my LEDs are incrementing through my strip, but I am not able to restart it until it passes though completely. I read that the while(); part in my code works kinda like a delay(); and that would prevent it from restarting until a full cycle. I used some millis(); code from a different sample so it's not like the ones from Blink Without Delay.
I searched so many sites and cannot write another code to increment without a delay, so hopefully you can help me with it.
#include <FastLED.h>

#define NUM_LEDS_PER_STRIP 16
CRGB ledStrip[NUM_LEDS_PER_STRIP];

const int signalButtonPin = 4;
const int ledStripPin = 8;

int buttonState = 0;
int lastButtonState = 0;

int delaySignalAnimation = 100;

unsigned long currentMillis = 0;
unsigned long previousMillis = 0;

void setup() {
  pinMode(signalButtonPin, INPUT_PULLUP);
  pinMode(ledStripPin, OUTPUT);
  FastLED.addLeds<NEOPIXEL, 8>(ledStrip, NUM_LEDS_PER_STRIP);
}

void loop() {
  buttonState = digitalRead(signalButtonPin);
  if (buttonState != lastButtonState) {
    if (buttonState == LOW) {
      fill_solid(ledStrip, NUM_LEDS_PER_STRIP, CRGB::Black);
      for (int i = 0; i < 16; i++) {
        ledStrip[i] = CRGB::Blue;
        FastLED.setBrightness(100);
        FastLED.show();
        currentMillis = previousMillis = millis();
        while (previousMillis + delaySignalAnimation >= currentMillis) {
          currentMillis = millis();
        }
      }
    } else {
      lastButtonState = buttonState;
    }
    fill_solid(ledStrip, NUM_LEDS_PER_STRIP, CRGB::Black);
    FastLED.setBrightness(0);
  }
  FastLED.show();
}

Thanks in advance for you help.

Firstly, good for you trying to avoid delay().
However your while loop pretty much does exactly what delay() does anyway.
Instead you need to change your way of thinking. Instead of "I want to light LEDs 0 to 15 in sequence" you need to instead think "I have 6 LEDs lit. Now I need to light the 7th".
Each time through the loop, if enough time has passed (check the BlinkWithoutDelay example) then light just one more LED.  Once you have lit all 16 you can then restart your sequence.
And when you know how to restart your sequence at the end you should also know how to restart the sequence when you press a button.
For example loop() might look something like this (untested):
void loop() {
    static uint8_t lednum = 0;
    static uint32_t animTicker = millis();

    if (millis() - animTicker >= 1000) { // Once per second
        animTicker = millis();

        lednum++;
        if (lednum > NUM_LEDS_PER_STRIP) lednum = 0; // This resets the sequence

        // Turn on up to lednum LEDs and turn off the others
        for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {
            if (i < lednum) {
                ledStrip[i] = CRGB::Blue;
            } else {
                ledStrip[i] = CRGB::Black;
            }
        }

        FastLED.show();
    }

    buttonState = digitalRead(signalButtonPin);

    if (buttonState != lastButtonState) {
        lastButtonState = buttonState;
        if (buttonState == LOW) {
            lednum = 0;
        }
    }
}

The key there is that the variable lednum contains the number of LEDs that you want to display. Once per second, controlled by millis(), the LEDs are updated to display that number of LEDs.

Thanks for answering to my question. I will look up your sketch and will respond how its going. Yes, I read that it would be the same as a delay. I saw some code using unit8_t or unit32_t but it scared me for using it because it looks scary :D.

Those are just specific sized variables.  "u" is "unsigned". "int" is "integer", and "x_t" is the number of bits.  uint8_t is the same as byte but is portable (byte is Arduino-specific). uint32_t is the same as unsigned long but again is portable over different architectures.

Alright, that sounds not so scary anymore, its like a short version of those words. Thanks.

I loaded your sketch in and I can now reset during the counts. Now I need to look how I can start the sequenz with the same button and that it would stop after 1 cycle, cause it runs over and over again, but thats what a loop is for :)

This is not an answer, but an expansion on Majenko's code.
It adds another layer between the button press and the led display functions to make the program more flexible
void loop() {

    static bool     tick          = false;                 // periodic trigger signal
    static bool     zap           = false;                 // enable signal to run sequence
    static bool     buttonClicked = false;                 // button moved from "released" to "pressed"

    static uint8_t  mode          = 0;                     // chooses the light sequence to run
    static uint8_t  lednum        = 0;

    static uint32_t animTicker    = millis();

    if (millis() - animTicker >= 1000) {                   // Once per second
        animTicker = millis();
        tick = true;                                       // set the tick flag
    }

    if (buttonClicked) {                                   // you could check for a double-click here
        buttonClicked = false;
        zap = !zap;                                        // start/stop with button  ... zap is used for the separation of the button click function and the display function
        if (zap) {
            lednum = 0;                                    // start animation sequence at beginning
            mode += 1; if (mode > 2) mode = 0;             // select the next mode .... this could be done with a double-click
        }
    }

    if (tick && zap) {
        tick = false;                                                   // clear the tick flag .... zap stays set for the duration of the animation sequence
        lednum++;

        if (lednum > NUM_LEDS_PER_STRIP) {
            zap = false;                                                // This stops the sequence (runs only once) ... use a counter if multiples are needed
        }

        else {
            switch (mode) {                                             // pick one of the sequences ....  only colors change in this example

                case 0:
                    for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {  // Turn on up to lednum LEDs and turn off the others
                        if (i < lednum) {
                            ledStrip[i] = CRGB::Blue;
                        } else {
                            ledStrip[i] = CRGB::Black;
                        }
                    }
                    break;

                case 1:
                    for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {
                        if (i < lednum) {
                            ledStrip[i] = CRGB::Red;
                        } else {
                            ledStrip[i] = CRGB::Black;
                        }
                    }
                    break;

                case 2:
                    for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {
                        if (i < lednum) {
                            ledStrip[i] = CRGB::Green;
                        } else {
                            ledStrip[i] = CRGB::Yellow;
                        }
                    }
                    break;
            }

            FastLED.show();
        }
    }

    buttonState = digitalRead(signalButtonPin);

    if (buttonState != lastButtonState) {        // button state transition
        lastButtonState = buttonState;           // new "last state"
        if (buttonState == LOW) {                // transition from "released" to "pressed"
            buttonClicked = true;
        }
    }
}

Hi jsotola, I see you have posted a state machine. I have moving forward to a state machine as well, but am not yet familiar with it. I will try to inplement your code and will share my progress. Does the double click takes aktion if I press the button twice directly after it, or does it count forever to the second press? Thanks for your code and your time to make it. :)

you have to implement double click function ... that example code does not have it ... the code is mostly meant to demonstrate that button presses should not directly cause an action to occur, unless the code is very simple ... as far as double clicks go, all you have to do is to "remember" when the last click happened ... if the time interval, between the previous click and the current click, is shorter than some chosen value, then a double-click is detected

a real life state machine example is yourself when you are driving a motor vehicle on city street and you approach an intersection that is controlled by a traffic light .... think of yourself as a microcontroller ... you continuously monitor the traffic light state in a loop and you take action as a result of your observation


text:
IR signal: different libs, different bit/byte ordering?
For IR sender at Nano Every (ATMega4809-based) I am using infrared4arduino to send simple remote control codes. I am double-checking those with a Nano-based receiver with IRrecvDumpV2 example from IRremote library but I am receiving something else what I am sending (I think):
The sender has the following code using Infrared4Arduino:
   IrSignal* sig=Nec1Renderer::newIrSignal(0,0x906f); // cmd 0x90
   IrSenderPwm::getInstance(true)->sendIrSignal(*sig,1);

but the receiver dumps (besides some garbage like 0-bit JVC and SANYO frames):
Encoding  : NEC
Code      : FFF609 (32 bits)
unsigned int  data = 0xFFF609;

0x00 and 0xff (first 2 bytes of the "packet") are device and its logical complement, those are fine.
The command sent as 0x90 (followed by its logical complement 0x6f) is decoded as 0xF6 (plus its logical complement 0x09). Why? Is it an accident that 906f is f609 backwards?
What's going on here?
I will try to run both sender and receiver with the same lib (IRremote is not ported to Nano Every) but before I go ahead, better ask. Perhaps I am only doing some IR-beginner's mistake.

The command sent as 0x90 (followed by its logical complement 0x6f)  ... how do you know this?

you picked data that reads the same no  matter which is the bit order ... 1001 is same both directions ... transmit code, such as 1000

@jsotola That's the way the protocol works, as far as I understand. Device ID (0x00 in this case), its bit complement 0xff (for redundancy) and then command 0x90 (0b10010000) and its bit complenment 0x6f (0b01101111, again for redundancy).

you chose symmetrical data ... 10010000 reads 0x90 in one bit order and 0x09 in the other bit order, so it is not obvious how the data is being transmitted and received ... instead choose something like 11000100 which reads 0xC4 in one bit order and 0x23 in the other bit order

Solved, see the answer below.

It is the receiver (IRremote-based) which is decoding bits in reverse order. IRremote and IRLib2 implement the NEC protocol incorrectly (both on sending and receiving sides). More details in the issue report https://github.com/bengtmartensson/Infrared4Arduino/issues/52 .


text:
Why does the function esp8266.available() always returns FALSE?
I am trying to develop an Home automation system using Arduino and ESP8266 Module. But stuck at the very first step while checking is esp8266.available() available or not. This function always returns FALSE. Looking for solution. Thanks in advance.
CONNECTION
Vcc -----> 3.3
CH_PD ---> Vcc
RX ------> 2 (Arduino pin)
TX ------> 3 (Arduino pin)
GND -----> GND (Arduino)

CODE
#include <SoftwareSerial.h>
#define DEBUG true
SoftwareSerial esp8266(2,3);

void setup(){
    Serial.begin(9600);   // Setting the baudrate to 9600
    esp8266.begin(9600);  // Set it according to your esp’s baudrate. Different esp’s have different baud rates.
    pinMode(11,OUTPUT);   // Setting the pin 11 as the output pin.
    digitalWrite(11,LOW); // Making it low.
    pinMode(12,OUTPUT);   // Setting the pin 12 as the output pin..
    digitalWrite(12,LOW); // Making pin 12 low.
    pinMode(13,OUTPUT);   // Setting the pin 13 as the output pin.
    digitalWrite(13,LOW); // Making pin 13 low.
    sendData("AT+RST\r\n",2000,DEBUG);            //This command will reset module to default
    sendData("AT+CWMODE=2\r\n",1000,DEBUG);       // This will configure the mode as access point
    sendData("AT+CIFSR\r\n",1000,DEBUG);          // This will get ip address and will show it
    sendData("AT+CIPMUX=1\r\n",1000,DEBUG);       // This will configure the ESP8266 for multiple connections
    sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // This will set the server on port 80
}

void loop(){
    if(esp8266.available()){  // ALWAYS FALSE
        // My codes
    }
}

UPDATE
At the very first run time, the function is returning TRUE and showing an error
deprecated conversion from string constant to char wwrite strings arduino esp8266.find("+IPD,")

for line number

Also asked at: https://stackoverflow.com/q/49093800 If you're going to do that then at least be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

connect RX to TX and TX to RX. pin 2 is RX in your SoftwareSerial. did you set the AT firmware to 9600 baud? available() returns the count of available bytes.

@per1234 I am really sorry for that. During post on Arduino community suddenly I lost my internet connection and thought question was not publish. Then I directly posted id on Stackoverflow with arduino tag.

@Juraj Please look at the line number 3 "SoftwareSerial esp8266(2,3);".  Should I still connect RX to TX and TX to RX?

if you want two devices to communicate over Serial, then always one must listen on receive pin what the other transmits on transmit pin. in your SoftwareSerial setup pin 2 is RX and pin 3 TX.

Yes, so is this the problem?

Constructor parameter order is RX, TX (see https://www.arduino.cc/en/Tutorial/SoftwareSerialExample). So when you're connecting the RX of the ESP8266 to the RX of the Uno, that's wrong because both chips just listen on the same line where nothing ever happens. The transmitter must be conencted to a receiver (RX to TX) and TX to RX. So yes, put RX (ESP) -> 3 (Arduino) and TX (ESP) ->2 (Arduino).

"Yes, so is this the problem?" Probably. Why don't you test it and check if it works? RX-TX is definitely correct, not RX-RX, TX-TX.

@idkfa Checked, but no change.

@MaximilianGerhardt, Now the only difference is Blue LED is blinking. Nothing else.

There is a questions about baud rate in my first comment.

@Juraj, yes, baud rate is 9600

the warning about deprecated conversion can be from the compiler, but not from esp8266. you throw a bunch of AT commands at the esp8266 in setup(), what do they return? why should be there data available in loop?


text:
Need help to set PWM frequency to 25kHz on pin 8 of Arduino Mega
I am trying to follow Need help to set PWM frequency to 25kHz and generate the same 25khz on pin 8 of arduino mega which is controlled by TIMER 4; I dont see any success; could someone please help?
Given below is the code I have tried based on an answer by @EdgarBonet in the linked post and  I tried on connecting fan pwm on each of the 3 pins 6, 7, 8 one by one and still cannot get the speed to change and the fan is just running at full speed;
void analogWrite25k(int value)
{
    OCR4A = value;
    OCR4B = value;
    OCR4C = value;
}

void setup()
{
    TCCR4A = 0;
    TCCR4B = 0;
    TCCR4C = 0;
    TCNT4  = 0;
    TCCR4A = _BV(COM4A1)
           | _BV(COM4B1)
           | _BV(COM4C1)
           | _BV(WGM11);
    TCCR4B = _BV(WGM13)
           | _BV(CS10);
    TCCR4C = _BV(WGM13)
           | _BV(CS10);
    ICR4   = 320;

    // Set the PWM pins as output.
    pinMode( 8, OUTPUT);
}

void loop()
{
    analogWrite25k(10);
    for (;;) ;  // infinite loop
}

edit2:
Thanks for the hints by @dannyf; I read the datasheet again and below is what I am trying now but even this is not working and I am really unable to figure out if something is not right in this; I am trying to set value of OCR4C only in analogWrite25k method since fan pwm line is connected to digital pin 8 of my Mega;
TCCR4A = 0;
TCCR4B = 0;
TCNT4  = 0;
TCCR4A = _BV(COM4C1)
      | _BV(WGM41);
TCCR4B = _BV(WGM43)
     | _BV(CS40);
ICR4   = 320;         // TOP = 320

Comments are not for extended discussion; this conversation has been moved to chat.

Found a properly working answer for the question finally; Thanks to KIV's answer on Need help to set PWM frequency to 25kHz on pin 8 of Arduino Mega to control speed of a 4-wire cpu fan  an additional usful thing he has added is to allow setting of duty cycle from serial monitor input for convenience while testing;
void analogWrite25k(int value)
{
    OCR4C = value;
}

void setup()
{
    TCCR4A = 0;
    TCCR4B = 0;
    TCNT4  = 0;

    // Mode 10: phase correct PWM with ICR4 as Top (= F_CPU/2/25000)
    // OC4C as Non-Inverted PWM output
    ICR4   = (F_CPU/25000)/2;
    OCR4C  = ICR4/2;                    // default: about 50:50
    TCCR4A = _BV(COM4C1) | _BV(WGM41);
    TCCR4B = _BV(WGM43) | _BV(CS40);

    Serial.begin(115200);

    // Set the PWM pin as output.
    pinMode( 8, OUTPUT);
}

void loop()
{
    int w = Serial.parseInt();
    if (w>0) {
        analogWrite25k(w);
        Serial.println(w);
    }
}

easy.

find a copy of the datasheet for your mcu;
go to the section about your timer;
figure out a prescaler setting that yields the maximum roll-over count;
pick the timer mode that supports the roll-over count;
write your own analogWrite() function;
[optional] if you wish to reuse the stock analogWrite(), make sure that roll-over count calculated in 3) is a valid data type for the stock analogWrite(). If not, increase the prescaler in 3) until it is.
done.

edit: i decided to give it a try.
the following code:
void setup() {
  // put your setup code here, to run once:
  pwm1Set(TMR1_PS8x, F_CPU / F_PWM1 / 8);       //ps = 8x, top = F_CPU / F_PWM / 8 = 80
  analogWrite(9, 20);                           //dc = 20/80=25%
  analogWrite(10, 40);                          //dc = 40/80=50%
}

void loop() {
  // put your main code here, to run repeatedly:
}

produced the following output on an ATMega328p's TIMER1.

i'm reasonably sure that the output is indeed 25Khz.
the code itself however is capable of generating pwm at other frequencies.
edit2: the same code on mega2560 generating 25Khz pwm on pin6/7/8:

code used for that is as follows:
  //ps = 8x, top = F_CPU / F_PWM / 8 = 80
  //DC on Pin 6 = 20/80 = 25,
  //DC on Pin 7 = 40/80 = 50,
  //DC on Pin 8 = 60/80 = 75,
  pwm4Set(TMR4_PS8x, F_CPU / F_PWM4 / 8); analogWrite(6, 20);  analogWrite(7, 40);  analogWrite(8, 60);

pwm4Set() is a copy of pwm1Set(). Both are simple enough: only 5 lines of code used.

thanks for the response but the question was specific to arduino mega 2560;

@dannyf - thanks for the edit and help on mega but I am not sure where to get the pwm1Set or pwm4Set functions; are they builtin functions or part of some additional library?


text:
Need help to set PWM frequency to 25kHz on pin 8 of Arduino Mega to control speed of a 4-wire cpu fan
This question is not same as the other one and this is more about employing the pwm signal to drive a CPU fan;
I am trying to follow the answer by Edgar Bonet on the question Need help to set PWM frequency to 25kHz and generate the same 25khz on pin 8 of arduino mega which is controlled by TIMER 4 and use this pwm signal to control the speed of a 4-wire cpu fan(with black, yellow, green and blue wires);
Following is my updated code for generating the pwm signal on timer 4
void analogWrite25k(int value)
{
    OCR4C = value;
}

void setup()
{
    TCCR4A = 0;
    TCCR4B = 0;
    TCNT4  = 0;
    TCCR4A = _BV(COM4C1)  // non-inverted PWM on ch. C
          | _BV(WGM41);  // mode 10: phase correct PWM, TOP = ICR4
    TCCR4B = _BV(WGM43)
         | _BV(CS40);   // prescaler = 1
    ICR4   = 320;      // TOP = 320

    // Set the PWM pin as output.
    pinMode( 8, OUTPUT);
}

void loop()
{
    analogWrite25k(10);
    for (;;) ;  // infinite loop
}

I have connected pin 8 on the mega to the pwm input on the fan(blue wire) but I dont see any variation in fan speed and fan seems to run at full speed;
I dont really have any means or tools to verify if its really generating a 25khz pwm signal but fan speed is not changing or if its not generating a 25khz pwm signal because of which there is no change in the speed of fan;
I am stuck at this point and any help on this would he highly appreciated;

can you fan accepts such a high frequency PWM signal?

yes, its a cpu fan used for intel cpus and the fan datasheet says the signal needs to be ideally 25KHz

you should be able to measure duty cycle with a DMM or even an LED; if it's getting adjusted, it would imply operation...

i dont have a DMM, how can it be measured with an LED? and the fan speed should be noticeable ideally since I tried values as low as 5 and 10 for duty cycle and I dont see any variation in fan speed;

the LED gets dimmer at low duty-cycle values. make sure to (dramatically) limit current when testing.

okay, thats a bit difficult at the moment since I dont have an LED handy :-(

I just added some code to read the RPM of the fan using the green wire which is the sense/tach wire and the RPM does not seem to go low for lower duty cycles;

Also, I see that the PWM signal is being generated at 25KHz on pin 8; I verified it by reading the pwm output from pin 8 on pin 9 as if it were coming from the the fan and the code at http://elimelecsarduinoprojects.blogspot.in/2013/06/measure-rpms-arduino.html helps print the frequency in hertz and it looks like approximately 25KHz;

Let us continue this discussion in chat.

I've just tested your setting with older "Alpine 64 GT" CPU Fan and it works as expected. I've just added parsing integers sent from serial monitor, so I don't have to change code anymore.
void analogWrite25k(int value)
{
    OCR4C = value;
}

void setup()
{
    TCCR4A = 0;
    TCCR4B = 0;
    TCNT4  = 0;

    // Mode 10: phase correct PWM with ICR4 as Top (= F_CPU/2/25000)
    // OC4C as Non-Inverted PWM output
    ICR4   = (F_CPU/25000)/2;
    OCR4C  = ICR4/2;                    // default: about 50:50
    TCCR4A = _BV(COM4C1) | _BV(WGM41);
    TCCR4B = _BV(WGM43) | _BV(CS40);

    Serial.begin(115200);

    // Set the PWM pin as output.
    pinMode( 8, OUTPUT);
}

void loop()
{
    int w = Serial.parseInt();
    if (w>0) {
      analogWrite25k(w);
      Serial.println(w);
    }
}

you have connected the pwm line of fan directly to pin 8 of mega right? or is there any additional circuitry?

https://www.amazon.in/Terabyte-CPU-Cooler-intel-LGA775/dp/B01BDOI9KE/ref=cm_cd_al_qh_dp_i thats the fan I have; could it be that the fan has 4 wires but is not a pwm fan??? these fans are used as CPU fans so I thought they must definitely respond to pwm; any thoughts?


text:
Arduino Uno with ESP8266-01 using PubSubClient with secure TLS
In my example, Arduino UNO (ATMEGA328p) connects using the SoftwareSerial library with the ESP8266-01 module.
Then I used the PubSubClient library to connect to the MQTT broker. The connection is to port 1883 and is not encrypted. Everything works fine.
How can this be done to make the connection encrypted (TLS) to port 8883 with the setting of my own CA certificate.
Example:
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <SoftwareSerial.h>
#include <PubSubClient.h>

...

static const char ca_cert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
)EOF";

...

SoftwareSerial wifiSerial(WIFI_RX, WIFI_TX);
WiFiEspClient WIFI_CLIENT;
PubSubClient MQTT_CLIENT;

...

void setup() {
  wifiSerial.begin(9600);
  WiFi.init(&wifiSerial);
  if (WiFi.status() == WL_NO_SHIELD) {
    printLog("WiFi shield not present");
    // don't continue
    while (true);
  }
  printLog("Connecting to AP ...");
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  ???   WIFI_CLIENT.setCACert(ca_cert);   ???
  printLog("Connected to AP");
}

if your certificate is signed by well known CA then the AT firmware accepts it. the WiFiEsp library has connectSSL on WiFiEspClient, but the PubSubClient will not use it. create WiFiEspSSLClient client which calls connectSSL() in connect().

if it is a client side private certificate, then you would have to upload it to esp for AT firmware to use it, if the AT fw version you use supports it or build the AT firmware with the key included


text:
SIM800L and DTH22
I am very new to arduino. I am build a model that will require SIM800L and DTH22. I want to know if I can power both from my arduino. DTH22 has a wide range of input voltage but I doubt of SIM800L. It says 3.4V-4.4V but one arduino forum said that it requires 2Amps of current. But many people simply connect it to arduino 3.3V. Can anyone with experience tell me about this? (I am asking as I fried the microcontroller in my previous project.) Should I get externel power supply or go forward with arduino?

What does the documentation with your SIM800L module say about how it should be powered? The Data Sheet states a maximum current of 2.0A during Tx burst and 200-450 mA in other modes. I would not recommend using the Arduino internal power supply. The DHT22 uses almost no power at all and can be easily powered from the Arduino.

Do not connect any GSM module to an Arduino board 3.3v
This SimCom GSM modules like sim800L or sim800C can take burst current of 2Amp in low network area to provide proper network and another thing is that below 3.4v and above 4.4v it will shut down automatically and you will get an Undervoltage & overvoltage warning AT response on UART before shutdown.
Another thing is that the 3.3v voltage regulator on the Arduino board can only handle up to 1Amp max and above 500ma consumption its temperature will rise and near 1A even more.
So the conclusion don't provide supply to sim800l from Arduino.


text:
Come out of loop and execute Setup again
I want to end loop at a specific time and start setup again. Is this possible? (I can explain reason in case you require).

As others have suggested, that is not how an Arduino program works. It runs the setup function once, and then calls the loop function repeatedly and forever until it is powered down or reset. You'll have to explain what you're trying to do in order for us to help you get it working.

You could just call setup() yourself:
void loop() {
    if (some_condition) {
        setup();  // reinitialize everything
        return;
    }
    // etc.
}

But, as Majenko puts it, if you nee to do that it looks like there is
something wrong with your methodology.
That being said, it would be less suspicious if you only need to
reinitialize some specific part of your program. In this case you can
make a separate function for these initializations, and call it both
from setup() and, when needed, from loop():
void init_foo() {
    // ...
}

void setup() {
    init_foo();
    // other initializations...
}

void loop() {
    if (some_condition) {
        init_foo();  // reinitialize foo
        return;
    }
    // etc.
}

Not directly, no. You can reboot the Arduino though so everything starts from scratch (either through the watchdog timer or wiring a GPIO pin to RESET and pulling it LOW), but if you find you need to do this sort of thing then you should rethink your methodology so that you don't need to do this sort of thing.


text:
Wire.endTransmission() hangs, but only, if wire.begin(); is called with an address (MKR WiFi 1010)
This code runs without issues, scoped and seen from serial output:
#include <Wire.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Wire.begin();
  Wire.onReceive(receiveEvent);

  while (!Serial);
}

void loop()
{
  Serial.println("1");
  Wire.beginTransmission(8);
  Serial.println("2");
  Wire.write(0x1);
  Serial.println("3");
  delay(100);
  Wire.endTransmission();
  delay(100);
  Serial.println("4");
  delay(500);
}

void receiveEvent(int howmany)
{
  delay(100);
}

This one hangs on Wire.endtransmission():
#include <Wire.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Wire.begin(10);
  Wire.onReceive(receiveEvent);

  while (!Serial);
}

void loop()
{
  Serial.println("1");
  Wire.beginTransmission(8);
  Serial.println("2");
  Wire.write(0x1);
  Serial.println("3");
  delay(100);
  Wire.endTransmission();
  delay(100);
  Serial.println("4");
  delay(500);
}

void receiveEvent(int howmany)
{
  delay(100);
}

The problem starts as soon as I assign an address in Wire.begin(). As I understand, a slave is also allowed to send data and temporarily becoming a master when addressing another device.

Is there another master on the bus, that would require the mkr to also be a slave?

Yes and no, I have three devices, master mkr, two trinket m0 slaves. I want to push data from the slaves to the master immediately when they receive said data. The way it is setup, data collision from the slaves is impossible as the master alterantely enables the sensors on the slaves (this is why I need it to be a master for coordination) but I also want to receive the data as soon as it arrives and not poll for it as I fear that might mess up my interrupts on the slaves.

While the wire library supports multi-master for AVR, it doesn't for ATSAMD.
Temporary promotion to master is disabled when given a slave address, so the program will hang on wire.endTransmission().

I want to push data from the slaves to the master immediately when they receive said data.

So that means, that each slaves becomes master directly after it has received data from the MKR. This is still a multi-master setup, even while you are avoiding collisions through a fixed protocol. The Wire library does not support multi-master.
But I also don't understand, why you would need this. Your protocol does this: The MKR sends data to a slave (triggering it and maybe also sending some commands). Then the slave should send data back to the master. Then the transmission ends. This is normally done in I2C with just one master. The master does a master write (via Wire.endTransmission() and sends some command data to the slave. The slave will prepare the data, that the master requested, in it's buffer. Then the master will start a master read (via Wire.requestFrom()) which reads the data from the slave.
So you don't need a multi-master setup for this. It does exactly, what you described, but with only one master.

I found out the Wire library actually does support multi-master, but not on the ATSAMD

I have no way to predict when the slave will receive it's data, so other than polling the slave continuously I won't know when the data arrived at the slave.

In your original plan, you wanted to prevent collisions by essentially polling the slaves (writing data to them, so that they answer them selfs with a master transmission). If that is not an option anymore, you should think about a different communication interface, that better supports multi master scenarios


text:
Esp8266 not responding to GET request from Android app created using MIT App Inventor
I hope I am posting this question in the right section.
I am making a Smart Home Project for my college semester finals. I am using an Atmega328p microcontroller along with an ESP8266 (Esp 01). The Atmega328p controls all the sensors and actuators and sends the data to Esp01 via serial communication.
I have created a web server on the Esp01 which I plan to access by creating an app using MIT App Inventor. My GET request is of the format "http://192.168.43.42/4" where the digit at the end is data I want to send to the server and the response I get from the server is of the format "12&0&34.8" where the '&' is used to separate different values.
My problem is , when I access the server from Chrome in my laptop I get the desired response but when I access it using the App , I get an error "Error 1101 :Cannot find the specified URL". The Esp01 is connecting to a hotspot from my phone and I have checked the IP assigned to the Esp01 to ensure my GET request is correct.
The code for Esp01 in Arduino IDE is here : https://gist.github.com/TheMagicSmoke/467d6227d670697464038056e22f302d
The blocks for the app made in App Inventor is below:

The GET request URL when entered from Chrome in laptop returns a blank page at first but upon refreshing Chrome I get the desired response I told earlier. And in the app , I have used a timer which queries the server with the same GET request every 2 seconds. But when I open the App the error keeps on popping up. Please suggest me a solution, I have googled this without any success.

Is MIT AppInventor something that runs locally on a device or computer on your network, or something that runs on a website somewhere?

I have edited the title as it seemed misleading. What I meant is that I am accessing the server using an Android app that was created using MIT App Inventor which is a website.

I'm finding it hard to find any concrete information, but it looks like the "app" on your phone may just be a front-end to the MIT web servers and the code actually runs on there, not your phone - which means that the code can't get at what is inside your network - only things that are on the internet.

You have misunderstood. The server is a local server which has been created on the esp8266. The application on my phone is sending a GET request to that server. Both my phone and the Esp8266 are on the same WiFi network. This has nothing to do with the servers at MIT.

No, you misunderstand. Like I said, I am not certain, but I think that AppInventor works like this:  1. you design your app. 2. the interface is displayed on your phone. 3. Interactions are sent from your phone to MIT. 4. MIT executes code. 5. MIT attempts to connect to your ESP8266. Your ESP8266 is not on the internet, and MIT is not on your local network, so MIT cannot connect to it.

I would suggest using some third-party communication system, such as MQTT (if AppInventor supports it), or switching to a real programming language that runs directly on your phone.

Is the phone on WiFi in the same network as the esp-01? (@Majenko, I helped here on SE with a project with App Inventor and there was no problem to access a local esp-01)

@Juraj The Esp01 is connecting to a hotspot from my phone

did you try to access the page from a browser on the phone?

@Majenko the Applications created using MIT App Inventor run code locally on the mobile and not through MIT servers. I am sure about this. Thank you for helping me. I have found out the solution and will post it below as an answer.

@Juraj thank you for helping me. I have found out the solution and will post it below as an answer.

Can Yo post. aia file? Many thx in advance.
Tom

I have found out the solution to this problem. The code that I had written in the Arduino IDE for the Esp8266 was not correct for handling the GET request.  It only accepted data as a simple Web Server and not as a HTTP server. I am posting the modified code below .
https://gist.github.com/TheMagicSmoke/adaae1e4d92f258c88184c8690e68f08

so I didn't look at your code (the first version). I expected that you used the WiFiWebServer example not a sketch, which expects data 10 milliseconds after connect, else it fails


text:
In a circuit with a switch and a pull-down resistor, why does the high impedance of the input not discourage current from flowing into pin?
I'm a beginner to Arduino and circuits. I've spent the last couple hours hung up on the concept of how current flows through switches and pull-down resistors, having read every thread and watched every YouTube video I could find on the subject.
I understand that pull-down (and pull-up) resistors are necessary in order to prevent pins from floating. What confuses me is that, if the input pins effectively have a built-in 100 megohm resistance (according to this page), then how is it that a 10k ohm pull-down resistor is enough to dissuade current from flowing directly into ground even when the switch is closed?
Here is a diagram of my circuit:

Am I conflating the high-impedance state of input pins with resistance more generally?
Would really appreciate any clarification on this. Thanks!

Huh? 5V across 10kohm is 500uA.

@IgnacioVazquez-Abrams Sorry, I'm not totally sure what you're getting at.

I'm not sure what your question means. Of course some current flows from the positive rail to ground when the button is closed. How much? Well...

@IgnacioVazquez-Abrams Ah, I'm wondering why all the current doesn't proceed across the resistor to ground when the switch is closed, given that there's a very high built-in resistance right before the pin. If I'm missing something really obvious, I apologize. You may be overestimating my knowledge here.

Ohm's Law

@IgnacioVazquez-Abrams Right, I feel like I have a working grasp of Ohm's Law, but can't see how it directly relates to my question. I've hit upon a mental block around how the current is flowing through this circuit from the point that it emerges from the closed switch / button. It seems to be skipping the path through the resistor and instead making its way through the wire into input 2. Is this correct?
Edit: The system is recommending I move this to chat to avoid a protracted discussion in the comments, but I don't have enough reputation to do that. Apologies if I'm making this hard.

Current goes through all possible paths simultaneously. A little goes into pin 2. A lot more goes through the resistor.

@IgnacioVazquez-Abrams Got it, thank you.

Yes, all of the current that flows goes through that resistor to ground.  That way almost all the voltage drops across that one resistor and you are able to read the voltage with the pin on the high side of it.  Only a very very small amount of current flows into the pin when you read a voltage.  It just needs to charge up a very small capacitor.

Thank you! Just to clarify high side vs low side (these terms are new to me) - in the diagram in my question, isn't my pin reading it on the low side, between ground and load? I'm getting my understanding of these concepts from this page. Let me know if I'm missing something.

But when you press the button, your pin is on the high side of that resistor.  The button has almost no resistance compared to the resistor, so all the voltage drops across the resistor.


text:
Ultrasonic sensor not getting reading while connecting to ESP8266
it's been week that i am having issue,that i can’t get ultrasonic readings
when i connect with my esp8266 wifi module ,everytime it gives 0 cm reading.My
both hardwares work perfectly if i connect them individually.
i also divided a code of ultrasonic and esp8266 for the debugging steps,both are working. but when i combine both code together i get no response. In my database server i get 0 distance.
Note: using external power of 5v for ultrasonic sensor.
Is there any logical problem? please help Sir thanks.
Here is a code
#include<ESP8266WiFi.h>
#include<ESP8266HTTPClient.h>
#define trigger 12
# define echo 13
float timex = 0;
float distance = 0;
float max_height = 0;
float extra_space = 4.00;

int TANK_SPECIAL_ID = 1;

void setup() {
    pinMode(trigger, OUTPUT);
    pinMode(echo, INPUT);
    Serial.begin(115200);
    delay(5000);
    WiFi.begin("AndroidAP", "lovely12");

    Serial.println("Setup Initiated\ n");

    while (WiFi.status() != 3) {
        delay(500);
        Serial.println("Waiting for connection");
        Serial.print("WiFi Status: ");
        Serial.println(String(WiFi.status()));
    }
    Serial.println(String(WiFi.status()));
}

void loop() {
        HTTPClient http;
        int Percentage = 0;
        digitalWrite(trigger, LOW);
        delayMicroseconds(2);
        digitalWrite(trigger, HIGH);
        delayMicroseconds(10);
        digitalWrite(trigger, LOW);
        delayMicroseconds(2);
        timex = pulseIn(echo, HIGH);
        distance = timex * 340 / 20000;

        if (max_height == 0) {
            Serial.println("Setting max_height");
            max_height = distance;
            Serial.println("max_height configured..5 seconds delay");
            delay(5000);
            Percentage = -1;
            Serial.print("MAX HEIGHT: ");
            Serial.println(max_height);
        } else {
            int revVal = int(distance / max_height * 100);
            Percentage = revVal– 100;
            Serial.print("Current Ratings: ");
            Serial.print(distance);
            Serial.print(" cm");
            Serial.print(" | Percentage: ");
            Serial.print(Percentage);
            Serial.println(" %");

        }
        if (distance > -1) {
            String Data = "x=" + String(Percentage) + "&y=" + String(max_height) + "&z=" + String(TANK_SPECIAL_ID);
            http.begin("http://zaptraff.atwebpages.com/IOT/IOTCON.php");
            http.addHeader("application/x-www-form-urlencoded");

            int sent = http.POST(Data);
            Serial.print("Request val: ");
            Serial.println(sent);
            //String httpPayload = http.getString();
            //Serial.println(httpPayload);
            if (sent > 0) {
                Serial.println("Data has been sent");
            } else {
                Serial.println("unable to send data");
            }
        }
        delay(1000);
    }
}

hello?????????????

Tell us what happens (exactly) and what doesn't happen, and perhaps you'll get more interest.

i put my all interest to sort out that problem, the exact problem is that my sensor is not giving the  distance reading.. when i try to upload that values to my server with ESP8266

i put my all interest to sort out that problem, the exact problem is that my sensor is not giving the  distance reading.. when i try to upload that values to my server with ESP8266

seems like nobody is intrested to solve my problem although i explained each and everything in post :/

Could you create a minimal, complete, verifiable example of your code please? Take out everything which isn't necessary to show the problem. For example i presume you don't need the http stuff.

if i takeout everything which isn't necessary to run only ultrasonic code, by discarding the esp8266code, than ultrasonic is working perfectly on switching the board to ARDUIO uno from tool bar. but the main problem is that when i add the http code for my esp8266 and change the board to generic esp than the sensor gives 0 value. Reason i added the http code is to send the sensor data to server.

i think i am wasting my time by posting problems here. worst website i ever seen

You may find that being grumpy and unfriendly is not the best way to attract help. We're not paid to be here - you need to make people want to help you. So, you had it working and then changed TWO things (added HTTP code and changed the board) and now it's not working. Does it still work if you only change one thing? If you find that out, you halve the problem space. Which change caused it to break?

As the MIME type implies application/x-www-form-urlencoded is URL encoded. Non-alphanumeric characters must be percent encoded.
It looks like this line:
if (distance > -1) {

Should be:
if (Percentage > -1) {

Further:
Percentage = revVal– 100;

Is sometimes negative. So String(Percentage) is producing - which is likely tripping up your web server because this is an illegal character when parsing x-www-form-urlencoded.


text:
Standard Practice for including custom library in examples folder
I have created my custom library with examples folder in them. The main header file is ABC_Node.h. I am referring the structure of Adafruit libraries for Arduino and in some repos under the examples folder I found a conflict for the inclusion of their header files.
Example
in some repos. they use double quotes ("") for including their header files e.g. #include "Adafruit_SHT31.h"
SHT31test.ino
on the contrary, in their BNO055 Arduino library they use brackets (<>) #include <Adafruit_BNO055.h> BNO055 Bunny sketch
I locally tested my library on the IDE and I have examples in which my library is in #include "ABC_Node.h" and it compiles without a problem.
Soon I wish to make the repository public and want to know if there is a standard practice for including header files for examples.

You can use either. There is no "standard".
When using a raw C compiler there is a difference between the two as regards the order in which directories are searched for files to include, but with the Arduino that is completely irrelevant, so either can be used.
Personally I use <...> for libraries and "..." for header files that form part of the sketch.  It makes for easier identification of which is which, and conforms to the C standard of <...> for system-installed headers, and "..." for local headers.

me too :-) (123)


text:
Possibility to program the ATmega32u4 on the Arduino Yun using a configuration file
Is it possible to send a Configuration File viz. conf.json that can be sent to the Arduino Yun via Ethernet and a Python Program can parse the configuration and set for example Sampling Rate of a Sensor which is connected to the 32u4?
The problem for me is that Sampling Rate in the Arduino Sketch is actually a preprocessor directive and I understand that C++/Arduino Sketches need to be compiled once before the changes take place.
However, how can I change the preprocessor directive in the sketch using a configuration file?
e.g.
#define SAMPLE_RATE (100)

in a conf.json file somewhere there might be:
{"sample_rate": 1000}

Once the .json file is parsed using python is it possible to change
#define SAMPLE_RATE (100) // to #define SAMPLE_RATE (1000)

You can't. You'll have to change your macro into a variable and change that variable when suitable data is received through the serial port.
You may also have to trigger a reconfiguration of whatever software is doing the sampling, or reconfigure the hardware, depending on what it is you are sampling.

What if I had the Sketch on the Yun on an SD Card and use sed to check the parameters and compile the code again using command line?

That would just be plain nasty. Using a variable instead of a #define should be simple enough, depending on what you are doing in your code with that value.

I think you are right in this sense. I might as well use the Atheros microprocessor as a middleware to store the data and then do stuff on python and nodejs scripts than on the Microcontroller. Thanks for the insight


text:
Arduino IDE does not display examples folder from my custom library
I have created a custom library for local usage. I call is ABC_node for ESP32 and the structure is as follows:
.
|-- examples
|   |-- bnoCalibStorage
|   |   `-- bnoCalibStorage.ino
|   |-- influxHTTP_write
|   |   `-- influxHTTP_write.ino
|   |-- influxPing
|   |   `-- influxPing.ino
|   |-- influxUDP_write
|   |   `-- influxUDP_write.ino
|   `-- rtcTimestamp
|       `-- rtcTimestamp.ino
|-- keywords.txt
|-- library.properties
|-- README.md
|-- ABC_Node.cpp
`-- ABC_Node.h

I tried following the Adafruit GitHub Repository structure where each example is placed inside a folder named after the sketch.
I am hosting this repository on a private GitLab Server. I used git tag v1.0.0 to create a tag and from GitLab I could download the .zip file for the stable v1.0.0 library.
I manually extracted the files to my <user>\Documents\Arduino\libraries folder and renamed the folder to ABC_Node (since my gitlab repo is named something else)
I restarted my IDE but I could not find the library ABC_Node in
Sketch\Include Library\

library.properties
name=ABC_Node
version=1.0.0
author=Shan Desai
maintainer=Shan Desai
sentence=Firmware to create InfluxDB measurements and send them via HTTP/UDP to Core
paragraph=ABC_Node provides `String` based InfluxDB measurements which can then be sent via HTTP/UDP to a central InfluxDB instance.
category=Data Processing, DAQ
architecture=ESP32
repository=https://[gitlab-address]/node-repo.git

I followed the Libraries Guide from Arduino on local Installation
System
Windows 10
Arduino IDE 1.8.5

Your library.properties is lacking a line.  Emulating your library with blank files and copying in your library.properties content, and running on Linux from the command line, it reports to me:
Invalid library found in /home/matt/Arduino/libraries/ABC_Node: Missing 'url' from library

So you lack the line:
url=https://whatever.website.you.want.to/point.to

(Or use something like http://example.com if you don't want one...)
I put that line in, and magically the library appears in the list.

Can you tell me what commandline you used here ?

You just run the Arduino program. No need for any options or anything.

so just execute it from the IDE?

Pardon?  Execute what from the IDE? On Linux at a BASH terminal prompt I typed, precisely, /home/matt/Downloads/arduino-1.8.5/arduino and it gave me that error on the screen as the IDE loaded.  I doubt you can do the same on Windows though...

That was what I was expecting as an answer. The commandline tool arduino. You are right it I am not sure if I can execute arduino on CMD or Powershell. Thanks.

You can run it from the command line, but whether it would give you any meaningful output on the command line is anyone's guess. You may want to run java -jar <path/to/arduino/jar/file> - you'll have to work out where the right jar file is though...


text:
MFRC522 won't detect cards after the first loop
Edit: I have found out that it was something wrong with the cables. I have solved the problem. Thanks for everyone who tried to help.
I am working a project that should basically do:

Read the RFID card UID.
Get the selection from user using pushbuttons.
Restart the code for new cards.

The problem is, It reads the card and gets the input from pushbuttons. But after the first loop, It doesn't detect other cards (or the same card again). Here is my code: (I am using miguelbalboa's MFRC522 library and Arduino UNO)
#include <MFRC522Hack.h>
#include <MFRC522Extended.h>
#include <deprecated.h>
#include <MFRC522Debug.h>
#include <require_cpp11.h>
#include <MFRC522.h>

// protype 1 copy
#include <SPI.h>

// Define pin numbers for mfrc522
#define SS_PIN 10
#define RST_PIN 9
#define BLUE_BUT A0
#define RED_BUT A1

// Define pin numbers for lcd
const int RS = A0 , EN = A1 , D4 = A5 , D5 = A4 , D6 = A3 , D7 = A2;
int uids[] = {14805 ,25673};
int votedArray[] = {};
String uidNames[] = {"WHITE" , "BLUE"};
// Create LCD and MFRC522 instances
MFRC522 mfrc522(SS_PIN , RST_PIN);

unsigned long getCardID(int showCardData = 0){
  /* this function gets the uid of the rfid card
   and returns the uid in unsigned long format */
  /* this fn. should be called with argument 1
  if printing the card data to the serial monitor
  is needed. */

  unsigned long UID_unsigned;
   UID_unsigned =  mfrc522.uid.uidByte[0] << 24;
   UID_unsigned += mfrc522.uid.uidByte[1] << 16;
   UID_unsigned += mfrc522.uid.uidByte[2] <<  8;
   UID_unsigned += mfrc522.uid.uidByte[3];

  if(showCardData==1){
  Serial.println("UID Unsigned int");
  Serial.println(UID_unsigned);

  String UID_string =  (String)UID_unsigned;
  long UID_LONG=(long)UID_unsigned;

  Serial.println("UID Long :");
  Serial.println(UID_LONG);

  Serial.println("UID String :");
  Serial.println(UID_string); } // print card data to the serial monitor
int UID_int = (int) UID_unsigned;
 return UID_int;

 }

void showCardData(){
  /* this fn. calls getCardID function
  with argument 1 to print the data to
  the serial monitor (kind of shortcut)*/
  getCardID(1);
}

int findInList(int uid , int uidArray[]){
  /* this fn. returns the index of the uid in the array if found,
  returns -1 if not found*/
  int numOfElements = sizeof(uidArray)/sizeof(uidArray[0]); // calculate the num.of elem. in array
  for (int i = 0 ; i <= numOfElements ; i++) {
    if(uid == uidArray[i]){
      return i; // if element is found in the array, return true
    }
  }
  return -1;
}

String getCardName(int cardUID){
  int UIDIndex = findInList(cardUID , uids);

  if(UIDIndex == -1){
    return "ERROR";
    }

  else {
    String cardName = uidNames[UIDIndex];
    return cardName;
    }

}

void printCardName(int cardUID){
  String cardName = getCardName(cardUID);
  if(cardName == "ERROR"){
    Serial.print("ERROR! CARD UID: ");
    Serial.println(cardUID);
    }

  else {
    Serial.print("CARD NAME: ");
    Serial.println(cardName);
    }
}

void setup() {
  Serial.begin(9600); // Init. serial comm. with the PC
  SPI.begin(); // Init. SPI bus for MFRC522
  mfrc522.PCD_Init(); // Init. MFRC522 card
  pinMode(BLUE_BUT , INPUT);
  pinMode(RED_BUT , INPUT);
}

void loop() {

    // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent()){
  Serial.println("CARD NOT PRESENT");
    return;
 }

  // Verify if the NUID has been readed
  if ( ! mfrc522.PICC_ReadCardSerial()) {

    Serial.println("CARD NOT read");
    return;  }

  int cardUID = getCardID();

  Serial.println("CARD UID READ");
  printCardName(cardUID);

  Serial.println("SELECT WITH BUTTONS");

//getVote(cardUID);
  int blueState = LOW , redState = LOW ;
  while(1) {
   blueState = digitalRead(BLUE_BUT);
   redState = digitalRead(RED_BUT);

  if(blueState == HIGH){
    Serial.println("BLUE");

    break;
    }

  if(redState == HIGH){
    Serial.println("RED");
    mfrc522.PICC_HaltA();
mfrc522.PCD_StopCrypto1();
    break;
    }

  }

Serial.println("PROGRAM COMPLETE");

}

I have already tried adding
    mfrc522.PICC_HaltA();
    mfrc522.PCD_StopCrypto1();

but didn't help.
And here is the screenshot of the Serial Monitor after reading the first card and getting the button input.

I have checked the similar problems, but the solutions didn't help me.

It's obviously returning on one of the two ifs at the start of your loop. Your job is to work out which.

Thanks for your reply Majenko, you are right and I have checked it. I have found out that the first if statement (PICC_IsNewCardPresent()) causing it. But what can be the problem, why doesn't it detect the cards ?

I think the clue might be the word "new" in there - it won't detect the same card twice (second time it's not new, it's old), and maybe the other cards are the same ID or maybe broken? Who knows...  Do you get the same result regardless of which card you try first?

I don't think it is due to cards, because when I run the code without the "getVote" part, It works fine: reads the card UID, prints the name of the card. Something in that part should be affecting the reader. And yes, the result is same regardless of the order of the cards.

Which pins are RED_BUT and BLUE_BUT?

A0 (blue) and A1 (red)

I can see nothing there that would cause it. Can you share your entire sketch? There may be something you assume is unrelated yet is the cause.

I added the entire sketch to the main post.

Nothing immediately jumps out at me, though I really don't like your copious use of String objects around the place.

I assume, Buttons and RFID reader both connected to the 3.3v pin on arduino. Move buttons to the 5v, leave RFID on 3.3v alone.


text:
5V pin out, 8 pins and micropython/circuitpython support: does such a board exist?
For a project, I am looking for a board to connect eight different neopixel-strips to, on eight different data pins. Because of the great length between the board and the first pixels of these strips, I'd like to have a board that operates on 5V instead of 3.3V. Then, the software that I have written to manage the LEDs is made in (micro)python. Finally, for simplicity's sake, I'd like to run this complete project on a single board without too many external components.
So, I have found 5V boards with enough pins, like the Arduino Mega. I have also found boards with enough pins and support for micropython or circuitpython, like the ESP32 or Arduino Zero.
However, I haven't quite found a board that matches all my requirements. The Arduino Mega doesn't support Python (or does it?) and the ESP32 and Arduino Zero operate at 3.3V, not 5V.
Of course, an ESP32 with a level shifter (as shown on https://github.com/Aircoookie/WLED/wiki) would work, but is there perhaps a board out there that fits all my requirements our of the box?
Edit: It seems I misunderstood some things about the hardware - sorry, I'm a software guy, not really a hardware guy :-) I fixed the question above as not to confuse future readers.

which therefore need to be capable of PWM -- Nope. PWM has nothing to do with Neopixels. Think again. ;; Because of the great length of these strips, I'd like to have board that operates on 5V instead of 3.3V -- Nope. The voltage, as long as it's above VIH of the first neopixel, has no effect on the rest of the chain.  Think again.

As many new boards are release every year and many others get discontinued, we cannot really keep track on all boards. I don't know about a board with your requirements. Though for me it is also not clear, why you are setting those requirements. As I remember, driving a Neopixel strip does not require a PWM pin. And what exactly has the length of the strip to do with the signal voltage level? I think each NeoPixel will output the rest of the data on its own, then using its supply voltage (meaning 5V). I can easily drive a small Neopixel strip with an ESP. Should also work with a long one

There are not so many ARM chips with 5V IO (I know only about SAMC20/SAMC21) with memory big enough to run micropython and that much strips. Btw teensy + octoWs2811 shows how could it be done (it's using DMA, several DMA channels connected to several trigger sources from timer)

Yes, @Majenko and chrisl, you were right. I thought again and have updated my question.

Why do you specifically want the strips on different pins?

I'm afraid otherwise the combined strip will be too long, @DaveNewton

Too long for what? How long are the strips?

too long to carry the current, I guess? The thing is that the strips are relatively far removed from the board (±5m) and different strips are also physically located at different positions sometimes a few metres apart themselves again.
I reckon that it's easier to wire each strip to the board instead of each strip to another strip. I'm just the software guy here, though - not in charge of the hardware in this project :-)

Both your "requirements" for the board are non-requirements.

You do not need PWM pins to drive Neopixel strips. The Neopixel uses its own custom protocol that has nothing at all to do with PWM.
Your board only communicates with the first Neopixel. That one then communicates with the second, which then communicates with the third, etc. The length of the strip is completely irrelevant to what voltage you might want to drive it with.

You only care about having enough general IO pins and if the IO voltage is suitable to communicate with one Neopixel.
According to the WS2812B datasheet VIH is 0.7Vdd, which if you are powering the strips from 5V means 0.7 * 5 = 3.5V. However I think that is an overestimation and they are erring on the side of caution there, since I regularly drive WS2812B strips from a 3.3V microcontroller with no problems whatsoever (after all it's only 0.2V difference).
So just use your favourite 3.3V microcontroller that can run micropython and, if you really want to, drop the power supply voltage to the strips a fraction with a diode.

It usually works from 3.3V without any problem. At most I've heard about low temperatures might cause it stops working. However I was thinking about using diode between power ground and MCU ground to add a bit offset (but I've never actually needed it)

Got it, thanks a lot. The PWM was indeed a non-requirement. The 5V comes from the fact that the board will be several meters away from the first neopixel (I misunderstood from our hardware girl, I'm just the software guy), but we'll be using a level shifter anyway now, so we're good.


text:
Unable to upload sketches to Sparkfun Redboard
I have two sparkfun redboards. Neither board will allow a sketch to be uploaded from the Arduino IDE.
I plug in a board and it powers on. In the Arduino software I select Tools->Port->COM4 (the only option) and Tools->Board->Arduino/Genuino Uno. Then compile and upload the Blink example. I get the following errors:
Sketch uses 928 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\andy\AppData\Local\Temp\arduino_build_463875/Blink.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x5f

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I understand that this is a fairly generic error indicating failure to communicate with the board, but I don't know what to do about it. I have various Arduino Unos and Arduino Megas and can upload sketches to them without a problem. Since it seems unlikely that both redboards are faulty (different batch numbers), I suspect a software problem relating to the ftdi-based serial comms used by the redboards.
I'm using Windows 10 x64 with Arduino IDE v1.8.5 and FTDI drivers v2.12.28.0 x64 (all latest). I've also tried another windows 10 machine and a different usb cable, with the same results.
I'd appreciate any suggestions.
Update
I've tried using an ftdi cable to connect to the boards on pins 0 and 1. I get the same error message.
I've also tried running avrdude manually and varying some of the parameters. No luck with that either.

Are you sure it's on COM4?

@Majenko Yes. With the board connected, device manager shows the only serial port as COM4. And COM4 is the only port choice offered by the Arduino IDE.

And without the board connected com4 vanishes?

does your PC make the bum-bum-ding sound when you plug in the board?

@Majenko Yes. When I disconnect the board, COM4 vanishes from the device manager and also Tools->Ports in the Arduino IDE, and the device manager shows no serial ports and Tools->Ports is greyed out.

@dandavis Yes. And a similar but different sound when I disconnect the board.

the programmer name may be incorrect

@jsotola I've gone through the list of programmer ids supported by avrdude but none seem applicable except "arduino". Maybe "arduino-ft232r" might work but I'm not using the ISP and am not sure of the pinouts.

jumper RX and TX (pin 0&1)  .... use the serial monitor in the arduino IDE .... type anything on the keyboard and see if it echoes back .... remove jumper and try again (just to make sure that it no longer echoes)

@jsotola Thanks for the suggestion. I tried the loopback test and I get characters echoed back to me. Removed the jumper and echoing stopped.

I've updated the question. Tried using an ftdi cable to connect to the boards on pins 0 and 1, and also tried running avrdude manually. No luck.


text:
How to generate two pulses one with 60 and other 66 duty cycle at same instant in 2 pins?
I have to drive two switches one at a duty cycle of 60% and the other at a duty cycle of 66% simultaneously at 50khz frequency. I am using an Arduino Uno ATmega 328.

Set Timer 1 to waveform generation mode 14, with both outputs in non-inverting mode and ICR1 = 319; OCR1A = 191; OCR1B = 210;.

I proposed a few approaches in generating 100kha pwm pulse trains here in response to someone's ask a couple of days ago. The identical code would work for your purpose as well.
It should come up quickly if you do a scan of topics here.
edit: to make it a little bit easier, here is the code I used to generate 50Khz pulse train with 60% and 66% duty cycles.
void setup() {
  // put your setup code here, to run once:
  //pinMode(led1, OUTPUT);                      //led1 as output
  //pinMode(led2, OUTPUT);                      //led2 as output
  pwm1topr(F_CPU / F_PWM);                      //set tmr1/pwm frequency to F_PWM
  analogWrite(led1, F_CPU / F_PWM * 60 / 100);  //led1 @ 60% duty cycle
  analogWrite(led2, F_CPU / F_PWM * 66 / 100);  //led2 @ 66% duty cycle
}

void loop() {
  // put your main code here, to run repeatedly:
    //digitalWrite(led, HIGH);  // turn the LED on (HIGH is the voltage level)
    //delay(100);               // wait for a second
    //digitalWrite(led, LOW);   // turn the LED off by making the voltage LOW
    //delay(100);               // wait for a second
}

and a quick sim confirms its functionality.

enjoy.

What's a kha ?  Also, please add link for the previous answer, instead of that copout.  Was it perhaps  how can i generate square pulse at 50khz frequency to drive two mosfets at a duty ratio .6, which is almost a duplicate of this question, except for having only one .6 duty cycle instead of a .6 and .66


text:
Powering SD breakout board with 3.7V battery
So in a previous post I asked if I could charge an SD card breakout board with a 3.7V LiPo battery, and I got a positive response, so I did it.
The problem is that it seems not to be enough, since, with the exact same wiring, if I supply it with my Arduino Uno, it works perfectly, but when I change the supply to the battery it gives an error. The following text is the result of an Arduino example script:
When connected with the Arduino:
Initializing SD card...Wiring is correct and a card is present.

Card type: SDHC

Volume type is FAT32

Volume size (bytes): 2696937472
Volume size (Kbytes): 2633728
Volume size (Mbytes): 2572

Files found on the card (name, date and size in bytes):
SYSTEM~1/     2017-04-27 15:20:04
  WPSETT~1.DAT  2017-04-27 15:20:04 12
  INDEXE~1      2017-04-27 15:20:14 76
TEST0.TXT     2000-01-01 01:00:00 49050
TEST1.TXT     2000-01-01 01:00:00 60231
TEST2.TXT     2000-01-01 01:00:00 1044
TEST3.TXT     2000-01-01 01:00:00 34831
TEST4.TXT     2000-01-01 01:00:00 189736
TEST5.TXT     2000-01-01 01:00:00 12419

When connected to the battery:
Initializing SD card...initialization failed. Things to check:
* is a card inserted?
* is your wiring correct?
* did you change the chipSelect pin to match your shield or module?

or
Initializing SD card...Wiring is correct and a card is present.

Card type: SD1
Could not find FAT16/FAT32 partition.
Make sure you've formatted the card

I've tried to supply the breakout board both through the 3V and 5V input. Can anyone notice what am I doing wrong?

Did you connect the ground of the SD card board to the ground of the Arduino?

no, i was connectiong to the ground of the battery, should it be the arduino's one?

Yes, all connected devices must share the same ground, otherwise they can't talk to each other.

Makes sense, so i don't connect the battery ground to anything?

Yes, you connect the battery ground to ground. There is only one ground. All "ground" points must be connected together.

Ahh, so in my breadboard i will put the arduino's ground and  the battery ground in series and from there i pull a cable to the breadboard's ground, correct?

It doesn't (much) matter how you connect all the grounds together, as long as they are all connected.

ahh great that was it, thank you, and sorry for the lack of knowledge in electronics.

Don't be sorry. You learned something today.

You haven't connected the grounds together in your circuit. You need to connect all the grounds together so every connection has a return path back to where it came from.  That means connect together:

An Ardino GND pin
The GND pin of the SD card breakout board
The negative (or ground) pin of the battery

authors: พรหมเมศร์ ไกรวิชัย


text:
Delaying an action inside a function
My current function is supposed to play a sound effect, then after the sound effect is done (14 seconds), perform the next action (digitalWrite(CONTROLLINO_R1, LOW)).
if (digitalRead(CONTROLLINO_A8) == HIGH && !skeleLatch) {
  skeleLatch = 1;
  wTrig.trackPlayPoly(2);
  unsigned long currentMillis = millis();
  if((currentMillis-previousMillis) >= 14000) {
    digitalWrite(CONTROLLINO_R1, LOW);
    previousMillis = millis();
  }
}

As it is, it performs both at the same time. I do not know how to correctly implement the delay so that it waits.
Any help would be appreciated. Thank you.

If your program shall not do anything during 14 seconds, why not simply use delay()?

its going into an escape room - meaning, there is a good chance someone else might activate something else while that music is playing.  In the off chance, i'd like to be sure it doesn't interfere with any other inputs

You can get the current time (milliseconds since startup) using millis(). Using that you can tell whether it's been 14 seconds since a particular event.  Does that give enough of a clue?

Where do you set up previousMillis (apart from after the decision in the code you posted)?

previousMillis was set to 0 unsigned long outside loop

  unsigned long triggerMillis = 0;

  if (digitalRead(CONTROLLINO_A8) == HIGH && !skeleLatch)
  {
    skeleLatch = 1;
    wTrig.trackPlayPoly(2);
    triggerMillis = millis();
  }

  if (millis() - triggerMillis >=14000 && skeleLatch)
  {
    digitalWrite(CONTROLLINO_R1, LOW);
    skeleLatch = 0;
  }

This should work, depending on how long your CONTROLLINO_A8 is staying high you might want to invest some more time to set up an interrupt on that pin, to make sure you don't miss a trigger.

If your code does not need to be re-entrant (work within a multitasking environment), the simpler solution is Arduino's delay function, designed specifically for waiting a specific number of milliseconds.
delay(14000)