text:
Parsing and comparing strings on Arduino: different behaviour from gcc?
I am trying to parse a simple string, print the result of the parsing via serial.println, and trigger a function on the basis of the received command. I wrote the code below, which perfectly works in c (see the c file attached). However, the behaviour of the same code on the arduino IDE is completely different and I really can't figure out why.
#include <string.h>

void rcv_msg(char *rcv_msg) {

  char *all_tokens[2];
  int i = 0;

  all_tokens[i] = strtok(rcv_msg, "{,}");
  while (all_tokens[i] != NULL) {
    all_tokens[++i] = strtok(NULL, "{,}");
  }

  char *command = all_tokens[0];
  char *value = all_tokens[1];

  /*
  //These printls do not work, they are ignored, why?
  Serial.println("all_tokens[0]: ");
  Serial.println(all_tokens[0]);
  Serial.println("all_tokens[1]: ");
  Serial.println(all_tokens[1]);
  */

  if (strcmp(command,"message_1") == 0 && strcmp(value,"1") == 0) {

    Serial.println("message 1: ");
    Serial.println(command);
    Serial.println(value);
    Serial.println(" ");

  }

  if (strcmp(command,"message_2") == 0 && strcmp(value,"0") == 0) {

    Serial.println("message 2: ");
    Serial.println(command);
    Serial.println(value);
    Serial.println(" ");

  }
}

void setup() {

    Serial.begin(115200);
}

void loop() {

    char msg1[] = "{message_1,1}";
    char msg2[] = "{message_2,0}";

    Serial.println("Send msg1: ");
    rcv_msg(msg1);
    delay(5000);

    Serial.println("Send msg2: ");
    rcv_msg(msg2);
    delay(5000);
}

This code gives the following output on the serial monitor, which is wrong:
Send msg2:
message 2:
message_2
{message_2,0}
Send msg1:
message 2:
message_1
{message_2,0}
Send msg2:
message 2:
message_2
{message_2,0}
Send msg1:
message 2:
message_1
{message_2,0}
Firstly, I don't understand why at the beginning, message 2 is printed before message 1, although message 1 was sent first. Second it is not clear to me the comparison done with strcmp is always returning the message 2.
More importantly, why running the same code in c has instead the correct output? I wonder if there is any error in my arduino code. BTW, I am testing the code on Teensy 3.2 but I plan to use it also on Arduino Uno.
The c code (which is perfectly working is this:
#include <string.h>
#include <stdio.h>

void rcv_msg(char *rcv_msg) {

    char *all_tokens[2]; //NOTE: the message is composed by 2 tokens: command and value
    int i = 0;

    all_tokens[i] = strtok(rcv_msg, "{, }");
    while (all_tokens[i] != NULL) {
        all_tokens[++i] = strtok(NULL, "{, }");
    }

    printf("all_tokens[0] : %s \n", all_tokens[0]);
    printf("all_tokens[1] : %s \n", all_tokens[1]);

    char *command = all_tokens[0];
    char *value = all_tokens[1];

    printf("command : %s \n", command);
    printf("value : %s \n", value);

    if (strcmp(command,"message_1") == 0 && strcmp(value,"1") == 0) {
        printf("activating command : %s %s \n\n\n", command, value);
    }

    if (strcmp(command,"message_2") == 0 && strcmp(value,"0") == 0) {
        printf("activating command : %s %s \n\n\n", command, value);
    }
}

int main() {

    char msg1[] = "{message_1, 1}";
    char msg2[] = "{message_2, 0}";

    rcv_msg(msg1);
    rcv_msg(msg2);

}

Both versions of your code have undefined behavior. On the given input your code will call strtok three times and store its result into the array three times: for the first token, for the second token and, finally, for the null pointer. You store all three (including that null pointer!) into the all_tokens array, which has size 2.
You are obviously aware of the potential array overrun danger: you even wrote this comment in your code
char *all_tokens[2]; //NOTE: the message is composed by 2 tokens: command and value

and yet in the following cycle
int i = 0;

all_tokens[i] = strtok(rcv_msg, "{, }");
while (all_tokens[i] != NULL) {
    all_tokens[++i] = strtok(NULL, "{, }");
}

you still insist on storing more than two values into all_tokens array.

Also, the second version of your code uses completely different message key values (why is it suddenly "motor1_pattern1" instead of "message_1"?), which makes it unclear how you compared the functionality of the second version with the functionality of the first.

many thanks. I added while (i < 2 && all_tokens != NULL)  which solved the problem. Is this the best way of doing it? Also I edited the code removing motor1_pattern with message_1 (sorry that was a bad copy-paste I did).  I still wonder:
Why the serial monitor still displays first the second message although the first message was sent. It seems that the first message does not reach the serial monitor... what I am missing?
Finally, do you suggest to use strtok_r instead of strtok?

Suggest to have a look at the message about memory usage while compiling. Arduino have only a small amount of RAM and string functions are using a lot. If your code is very small, it can work, but the more you'll increase the size of code and the more you'll get strange results.


text:
cannot upload my program to arduino uno
I bought new Uno yesterday, i made my programme, and i compile it. it was good compiled. however, when i upload the programme to my Uno, it cannot be uploaded and there was a message like this
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x1b
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
Help me please

so, did you read the troubleshooting web page?

Yes of course i did

Make sure u have selected the right COM port
Make sure nothing is connected to the pin 0 and 1 in arduino

This happens because the Arduino IDE could not find Arduino Board Connected to the system.

source: Stack Exchange

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

sort: votes


text:
Programing AVR 32u4 via ISP with other ISP device connected
I have a custom PCB with an Atmega 32u4 chip.  I program the chip with AVRDUDE via ISP after it is has been mounted onto the PCB. All is well.
I now want to add wireless capability via the NRF24L01.  The NRF communicates with the 32u4 via ISP.  Can I still program the 32u4 on the PCB after the NRF has been mounted or will there be a problem since they are both connected to the ISP pins?

Yes, that is possible and I've done the exact same thing with an ATmega328 which controls a DAC via SPI. If it wasn't possible ISP wouldn't be an option whenever SPI is already in use.
You should make sure that the NRF's CS pin is high while flashing the firmware, otherwise it might corrupt a checksum verification or memory readout.
Note the difference between ISP (in-system programming) and SPI (serial peripheral interface). Even though ISP uses SPI and they have similar abreviations they are not the same.

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


text:
Can a Arduino Uno handle all these components?
Its my first project with an Arduino, so please bear with the dumb questions.
For this project of mine, I need an Ultrasonic Sensor, a Gyroscope, a Buzzer, three push buttons and an 16x2 LCD.
Can I connect all these components at once to an Arduino Uno? I mean will I run out of pins or not? Should I go for a Mega 2560 (will have to buy one though).
Edit: a GSM sim800 as well lol

ultrasonic s. 2 pins, buzzer 1 pin, buttons 3 pins, gyroscope i2c? 2 pins, LCD i2c? same two pins, not i2c LCD  6 pins. Uno has 13 pins.

Yeah getting I2C for LCD, but I don' think the gyro comes with one. Here's the link to it: gyro

The gyro is I2C too

I think you're fine depends on the gyroscope model and lcd.
-For ultrasonic sensor thats 2 pins
-the lcd needs at least 6pins but with an i2c adapter you only need 2 pins
-3 push buttons 3 pins
-one pin for the buzzer
Plenty of room left on the uno

Thanks for replying. So if I get a i2c, I'll be good to go? Here are the links to the components: Gyro Ultrasonic I2C Buzzer


text:
How to get Json String from URL?
I want to get JSON string from a URL which goes like this

https://maps.googleapis.com/maps/api/directions/json?origin=7649+Paseo+Santa+Cruz&destination=SJSU&key=MY_API_KEY

and here is my code:

#include <Bridge.h>

//#include <b64.h>
#include <HttpClient.h>

//#include <ArduinoHttpClient.h>

#include <Arduino_JSON.h>
#include <SPI.h>
#include <WiFiNINA.h>

//#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = "my_wifi_ssid";        // your network SSID (name)
char pass[] = "my_wifi_password";    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;     // the Wifi radio's status

WiFiSSLClient wifi;
char serverAddress[] = "maps.googleapis.com";

void setup() {
  //Bridge.begin();
  Serial.begin(9600);
  //listNetworks();
  //Initialize serial and wait for port to open:

  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < "1.0.0") {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

  // you're connected now, so print out the data:
  Serial.print("You're connected to the network");
  printCurrentNet();
  printWifiData();
  Serial.println("\nStarting connection to server...");
  // if you get a connection, report back via serial:
  if (wifi.connect(serverAddress, 80)) {
    Serial.println("connected to server");
    // Make a HTTP request:
    wifi.println("GET /maps/api/directions/json?origin=7649+Paseo+Santa+Cruz&destination=SJSU&key=MY_API_KEY");
    wifi.println("Host: maps.googleapis.com");
    wifi.println();
  }
}

void loop() {
  while (wifi.available()) {
    char c = wifi.read();
    Serial.write(c);
  }

  // if the server's disconnected, stop the client:
  if (!wifi.connected()) {
    Serial.println();
    Serial.println("disconnecting from server.");
    wifi.stop();

    // do nothing forevermore:
    while (true);
  }

  // check the network connection once every 10 seconds:
  delay(10000);
  }

It only printed in Serial Monitor:
Starting connection to server...

disconnecting from server.

Bridge.h is for Yun. remove it. and change the unsuitable variable name wifi to client

you connect for https to port 80? default https port is 443. use wifi.connect(serverAddress, 443)

Better use <WiFiClientSecure.h> example


text:
Power Arduino controlled by another Arduino by MOSFET
I would like to control power to Arduino B from signal of digital pin from Arduino A.
I use IRFZ44N MOSFET as switch and +12V DC source. The Arduinos have common ground. The connection is:

Gate: signal from Arduino A (+5V or 0V)
Source: +12V
Drain: Vin of Arduino B

At this settings Arduino B is powered regardless of the value on the gate. What am I doing wrong and how should I change the settings to get the desired result? I know I misunderstand how the transistor works, please show me the correct approach.

share your schematic here and sketch using to control the gate voltage.

That mosfet has a body diode between the Source and Drain. So this diode will always let current though, no matter what the voltage is at the Gate. That N-channel mosfet isn't ideal for high-side switching. It would require additional circuitry, and even an extra power source as far as I can see. It's a lot easier to do low-side switching. That is; switching the GND instead of 12V.

@Gerben you mean to connect +12V directly to the Vin of Arduino B, Source of the N-MOSFET to ground and Drain to GND pin of Arduino B? Can the signal from Arduino A to the Gate switch the power correctly then?

Yes, that's what I meant. But you have to be careful if you have any other connections between the two Arduinos (for example a wire between TX and RX of the two Arduinos).

@Gerben indeed, I just fired up two GPIOs: to set the pin to LOW and close the transistor gate was not the brightest idea. Is there any simple solution to prevent damage when the GND pin accidentaly disconnects?

Adding a resistor will help. It will limit the current. The other thing to do is set any OUTPUT pins to INPUT, before turning of the power to the second Arduino. (You can also set them to HIGH, but I prefer the safety of setting it to INPUT). That way no current can flow from the second arduino, though the internal clamping diodes in the Arduino's MCU, to the LOW OUTPUT pin of the first Arduino.

You have an N-channel MOSFET. That is not suitable for switching the 12V supply of an Arduino.
Instead you need a P-channel MOSFET which has the gate pulled up to 12V using a resistor, and then an N-channel logic level MOSFET which is used by the Arduino to pull the gate of the P-channel MOSFET LOW to turn it on.
Something like:

simulate this circuit – Schematic created using CircuitLab
When the GPIO is HIGH it turns M2 on. This pulls the gate of M1 down, turning it on. When GPIO is LOW, or not actively being driven (thus being pulled down by R2), M2 is off. This allows the gate of M1 to be pulled up to +12V by R1, switching M1 off.

Thank you for the nice design. Would it be possible to pull the M1 gate to just +5V and open it by writing LOW to GPIO? (Without M2)

No. That is why you have m2 in the circuit. M1 has to be pulled to 12v. That's how a MOSFET works.

@JanTuroň A P-channel MOSFET's "threshold" voltage is the voltage of the gate below that of the source. It's listed in datasheets as a negative voltage. With the source at 12V the gate has to be at the source voltage to be fully off, or below 12V minus the threshold voltage to be on.  You can turn it on, but never off, if you can't get the gate up to (or very near) the source voltage.


text:
ARDUINO PROGRAM
I have a project that consists in measuring the mass of an object with a strain gauge HX711.
so I found an interesting Arduino program and the editing that goes with it.
but I have a problem, I manage to compile the program and then upload it but unfortunately my serial monitor still displays 0lbs.....
can you help me????
#include "HX711.h"

#define DOUT  3
#define CLK  2

HX711 scale;

float calibration_factor = -1242; //-7050 worked for my 440lb max scale setup

void setup() {
  Serial.begin(9600);
  Serial.println("HX711 calibration sketch");
  Serial.println("Remove all weight from scale");
  Serial.println("After readings begin, place known weight on scale");
  Serial.println("Press + or a to increase calibration factor");
  Serial.println("Press - or z to decrease calibration factor");

  scale.begin(DOUT, CLK);
  scale.set_scale();
  scale.tare(); //Reset the scale to 0

  long zero_factor = scale.read_average(); //Get a baseline reading
  Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
  Serial.println(zero_factor);
}

void loop() {

  scale.set_scale(calibration_factor); //Adjust to this calibration factor

  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 1);
  Serial.print(" lbs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
  Serial.print(" calibration_factor: ");
  Serial.print(calibration_factor);
  Serial.println();

  if(Serial.available())
  {
    char temp = Serial.read();
    if(temp == '+' || temp == 'a')
      calibration_factor += 10;
    else if(temp == '-' || temp == 'z')
      calibration_factor -= 10;
  }
}

Hint: Start by removing 1 from Serial.print(scale.get_units(), 1);

yes and @MikaelPatel

I removed the variable but now my serial monitor no longer displays a value?
I would like him to give me the value of a weight of 1kg  .@MikaelPatel

To find the error you need to remove any possible source. Removing the number of decimal digits could help detect if you are measuring a small value. The next (or actual first) thing to check is the wiring and the power supply.

I have to check the power supply all is good so I will remove the decimal numbers but I don't see how this could help me? @MikaelPatel

even when trying to remove the decimal numbers I always stay at 0 …. @MikaelPatel

What is the calibration factor? And how did you calculate that? Or did you just copy that?

My guess (given that the device and wiring are working) is that the scaling/calibration factors are wrong for the weight interval you wish to measure. Please check these settings.

i calculate the calibration factor with another program that consiter to read only the calibration value! @Mikael Patel

Plese ..? @Mikael Patel


text:
Python script not reading from serial unless teensy is rebooted
I want to send some analog sensor data from a Teensy 3.2 to a mac running a python script (I am using the usual pyserial module and I send data using Serial.print() in the arduino sketch). I am using Teensy but I guess the same would be true for an Arduino Uno.
The teensy is correctly sending on the serial port the data, as I can see it using the serial monitor. However, only the first time that I run the python script the data are handled by the script itself, if I stop the script then no data seem to be read in the serial buffer. To make the script work I necessarily have to re-launch the Arduino IDE and then upload the sketch.
Indeed the second time I run the script (after having stopped it), I can see that the pyserial function serial_port.inWaiting() does not give any data.
if (serial_port.inWaiting() > 0):
   print("serial_port.inWaiting() > 0") # does not print anything the second time I launch the script

I have checked that the second time that I launch the script the serial connection is open (using self.serial_port.isOpen())
What is preventing the python script to get the serial data the second time? Why serial_port.inWaiting() is not seeing that there is data in the input buffer?
In the arduino sketch code I have added the line while(!Serial); in void setup()
EDIT: I post the code. This is the arduino code (I am testing on teensy so no initial handshaking is required as teensy will not reboot)
int sensor = 0;

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

void loop() {

  sensor = analogRead(0);
  Serial.print(sensor);
}

And this is the python code:
#!/usr/bin/env python3

import serial
import time
import signal
import sys

def keyboard_interrupt(signal, frame):
    serial_port.close()
    time.sleep(2)
    exit(0)

serial_port = serial.Serial("/dev/tty.usbmodem1225061", 115200)

signal.signal(signal.SIGINT, keyboard_interrupt)
signal.signal(signal.SIGTERM, keyboard_interrupt)

if serial_port.isOpen():
    print(serial_port.name + ' is open...')

while True:
    if (serial_port.inWaiting() > 0):
        sensor = serial_port.read().decode("utf-8")
        print('sensor: "{}" '.format(sensor))

I discovered so far that in_waiting is returning 0 after the script is launched the second time. I can't figure out why. Any idea?

Serial communication is always terminated with a specific character (usually \n). The receiving device will accumulate the incoming bytes in a buffer until it receives this terminating character.
To fix the problem simply change the last line of your arduino loop to Serial.println(sensor);
Also note that the arduino might be faster than your python script, meaning that you will get several sensor values per readout. If that's the case you have to add a short delay in the arduino loop.


text:
Loop failure after unset amount of time
I am building an art piece that takes in input from three rotary encoders and two buttons. and outputs data to a large neopixel display and 2 large 4 digit seven segment displays. The displays are powered by the arduino 5V the neopixels are powered by a separate power source.
Everything works exactly as expected for a time. Then seemingly at random the code discontinues responding to any input. The seven segment displays continue to light up.
I believe it might be a power issue with the arduino overheating due to the power consumption of the seven segment displays (~300mA), however, the arduino is still "on" or reviecing power.
I have attached my code below as I worry that problem might come from a runtime error there rather that a power issue.
//3 rotary encoders
//2 buttons

//Displays:
//1 8x32 neopixel array
//2 4 digit 7 segment displays
//2 button LEDs

#include <Adafruit_NeoPixel.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include "Adafruit_LEDBackpack.h"
#include <Adafruit_VS1053.h>

//Music Maker Logic/Variables
#define mp_mcs 7
#define mp_dcs 6
#define mp_dreq 3
#define mp_ccs 4
#define mp_reset -1

char* music="TRACK001.wav";

//Music maker constructor
Adafruit_VS1053_FilePlayer mp =
  Adafruit_VS1053_FilePlayer (mp_reset, mp_mcs, mp_dcs, mp_dreq, mp_ccs);

//Neopixel Logic/Variables
#define neoPixelPin 26
#define pixelNumber 256
#define neoInterupt 50

Adafruit_NeoPixel neoArray = Adafruit_NeoPixel(pixelNumber, neoPixelPin, NEO_GRB + NEO_KHZ800);
uint32_t color;
bool flip;
bool nullColor[32] = {false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false};
bool colorTable[32] = {false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false};
long currentTime;
long pastTime;
long startingTime;
long pastTimeAlt;

//Encoder Logic/Variables
#define outputA1 40
#define outputB1 41
#define outputA2 42
#define outputB2 43
#define outputA3 44
#define outputB3 45

byte a1State;
byte a1LastState;
byte a2State;
byte a2LastState;
byte a3State;
byte a3LastState;
byte topDay;

//7 Segment Logic/Variables
Adafruit_7segment matrix1 = Adafruit_7segment();
Adafruit_7segment matrix2 = Adafruit_7segment();

byte month = 1;
byte day = 1;
short year = 2000;
String holder;
String holder1;
String holder2;

//button Logic/Variables
#define altResetPin 30
#define engPin 32

void setup() {
  Serial.begin(9600);
  //Serial.println("In setup");
  //Input initializations
  pinMode(altResetPin, INPUT_PULLUP);
  pinMode(engPin, INPUT_PULLUP);
  pinMode(outputA1, INPUT_PULLUP);
  pinMode(outputB1, INPUT_PULLUP);
  pinMode(outputA2, INPUT_PULLUP);
  pinMode(outputB2, INPUT_PULLUP);
  pinMode(outputA3, INPUT_PULLUP);
  pinMode(outputB3, INPUT_PULLUP);
  //pinMode(neoInterupt, INPUT);

  Serial.println("made it to structures");

  //begin structures
  neoArray.begin();
  neoArray.setBrightness(75);
  neoArray.show();
  Serial.println("Neo Array initialize");
  matrix1.begin(0x70);
  matrix2.begin(0x72);
  matrix1.setBrightness(4);
  matrix2.setBrightness(4);
  Serial.println("matrix initialize");
  //attachInterrupt(digitalPinToInterrupt(engPin), neoPixelSuprise, LOW);

  Serial.println("made it to initializations");

  //Music Player initialization
  if (! mp.begin()) {
   Serial.println(F("Music Maker connection failed, or not present"));
   while (1); // don't do anything more
  }
  Serial.println(F("Music Maker connection successful"));

  //SD card Check
  if (!SD.begin(mp_ccs)) {
   Serial.println(F("SD failed, or not present"));
   while (1);  // don't do anything more
  }
  Serial.println(F("SD Inserted and found"));

  mp.setVolume(10,10);
  mp.useInterrupt(VS1053_FILEPLAYER_PIN_INT);

  //initial Reads
  a1LastState = digitalRead(outputA1);
  a2LastState = digitalRead(outputA2);
  a3LastState = digitalRead(outputA3);

  //initial Outputs
  matrix1.print(combine(month,day),DEC);
  matrix1.writeDisplay();

  matrix2.print(year,DEC);
  matrix2.writeDisplay();

}

void loop() {
  //read current states
  a1State = digitalRead(outputA1);
  a2State = digitalRead(outputA2);
  a3State = digitalRead(outputA3);

  //deal with encoder readings
  //first encoder, encodes the month
   if (a1State != a1LastState){
     // If the B state is different to the A state, that means the encoder is rotating clockwise
     if (digitalRead(outputB1) != a1State) {
       //clockwise rotation
       if(month == 12){
        month = 1;
       }else{
        month ++;
       }
     } else {
        //cc-rotation
       if(month == 1){
        month = 12;
       }else{
        month--;
       }
     }
    }
   a1LastState = a1State; // Updates the previous state of the outputA with the current state

   //second encoder, encodes the day
   if (a2State != a2LastState){
     // If the B state is different to the A state, that means the encoder is rotating clockwise
     topDay = daysInMonth(month,year);
     if (digitalRead(outputB2) != a2State) {
       //clockwise rotation
       if(day >= topDay){
        day = 1;
       }else{
        day ++;
       }
     } else {
        //cc-rotation
       if(day == 1){
        day = topDay;
       }else{
        day--;
       }
     }
    }
   a2LastState = a2State; // Updates the previous state of the outputA with the current state

   //third encoder. encodes the year
   if (a3State != a3LastState){
     // If the B state is different to the A state, that means the encoder is rotating clockwise
     if (digitalRead(outputB3) != a3State) {
       //clockwise rotation
       if(year == 2100){
        year = 1900;
       }else{
        year ++;
       }
     } else {
        //cc-rotation
       if(year == 1900){
        year = 2100;
       }else{
        year--;
       }
     }
    }
   a3LastState = a3State; // Updates the previous state of the outputA with the current state

  //update 7segment display
  matrix1.print(combine(month,day),DEC);
  matrix1.writeDisplay();

  matrix2.print(year,DEC);
  matrix2.writeDisplay();

  //read buttons and act on them
  if(digitalRead(altResetPin)==HIGH){
    day = 1;
    month = 1;
    year = 2000;
  }

  if(digitalRead(engPin)==LOW){
    neoPixelSuprise();
  }
}

void neoPixelSuprise(){
  //put a crazy neopixel event here
  Serial.println("EngPin Hit");
  startingTime = millis();
  pastTime = millis();
  currentTime = millis();
  pastTimeAlt = millis();
  bool holdList[32] ={false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false,false};
  byte counter = 0;

  mp.startPlayingFile(music);

  while(currentTime - startingTime > 8000){
    currentTime = millis();

    if(currentTime - pastTimeAlt> 100){
      colorTable[counter] = flipper(colorTable[counter]);
      colorTable[31-counter] = flipper(colorTable[31-counter]);
      pastTimeAlt = currentTime;
    }

    //flickerControl
    if(currentTime - pastTime > 50){
      flip = flipper(flip);
      if(flip){
        fillRow(colorTable);
      }else{
        fillRow(nullColor);
      }
      pastTime = currentTime;
    }

    counter = counter+2;
    if(counter>31){
      counter = 0;
    }
  }
}

void fillRow(bool truthList[32]){
  //fills the panel with random color
  for(int i=0; i<32; i++){
    randomSeed(analogRead(A11));
    if(truthList[i]){
      //fills particular row with random color
      for(int j=0; j<8; j++){
        color = Adafruit_NeoPixel::Color(random(255),random(255),random(255));
        neoArray.setPixelColor((i*8)+j,color);
      }
    }else{
      //turns off particular row
      for(int j=0; j<8; j++){
        color = Adafruit_NeoPixel::Color(0,0,0);
        neoArray.setPixelColor((i*8)+j,color);
      }
    }
  }
}

bool flipper(bool whatIs){
  //flips a boolean
  if(whatIs){
    whatIs = false;
  }else{
    whatIs = true;
  }
  return whatIs;
}

byte daysInMonth(byte month, byte year){
  //based on the year it will tell you how many days there were in that given month
  //leap year condition, if month is 2
  if(month == 2){
    if((year%400==0) || (year%4==0 && year%100!=0)){
      return 29;
    }else{
      return 28;
    }
  }
  //months which have 31 days
  else if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month==12){
    return 31;
  }else{
    return 30;
  }
}

short combine(byte month, byte day){
  //takes the two bytes and truns them into one long digit
  holder1 = String(month);
  holder2 = String(day);

  if(holder1.length()==1){
    holder1 = "0" + holder1;
  }
  if(holder2.length()==1){
    holder2 = "0" + holder2;
  }

  holder = holder1 + holder2;

  return(holder.toInt());
}

don't use String class

char* is equivalent correct? I will look it up as well, however, what is so wrong with String class?

https://majenko.co.uk/blog/evils-arduino-strings

Your combine() function seems like you were searching for the most convoluted way of computing 100*month+day.

@Juraj thank you for the cool link!

@EdgarBonet you are completely correct. In retrospect it is super dumb. Thank you for pointing it out.


text:
Arduino only works properly when I'm touching it
I'm working on a arduino proyect, but I encountered a problem that I dont know how to solve.
The only thing I have done in the hardware part is connect the arduino nano to a power source (phone charger) through the 5v and Ground pins, but the built-in leds tell me that the code isn't running as it should be.
The TX led (Serial output) should be constantly on (because the code is always printing out things to the monitor), but instead it turns on and off in a longer interval of time, the code is running slower than it should be.
This stops when I touch ground with my finger or when the arduino is connected to a computer.
When I searched for a solution I found that most of the time this problem was related to missing connections to ground, and here seems to be the same, but the only thing I have connected is the arduino.
Any idea of what's happening and how to solve it?
To give more context, what I'm trying to do is a thermostat that can take a value of temperature and time, and turn on or off a relay. This relay is the one that opens or closes the electrical circuit of the lab's stove depending on the temperature and the time.
There are 4 buttons:
AUMENTAR ("increase" in english): increases the value selected in 5 (when pressed has a delay of 0.5 seconds).
DISMINUIR ("decrease"): decreases the value selected in 5 (when pressed has a delay of 0.5 seconds).
SIGUIENTE ("next"): changes the value you are editing (has no delay).
INI_DET ("start/stop"): starts or stops the machine (has no delay).
Code:
#include <max6675.h>
#include <LiquidCrystal.h>

//
// VARIABLES
//

// Machine's phisical state
int temperatura = 0; // en °C
int temperatura_prev;
// int humedad;
bool maquina_en_funcionamiento = false;

// User's variables (con la maquina no funcionando)
int array_de_valores[] = {20,10};     // valores editables por el usuario
int valor_seleccionado = 0;             // valor que se esta editando (por defecto, temperatura): 0=Temperatura, 1=Tiempo, 2=Humedad
// Variables visibles para el usuario (con la maquina funcionando)
int array_de_opciones[] = {0, 0};       // opciones visibles para el usuario
int opcion_seleccionada = 0;            // opcion visible (por defecto, maquina): 0=Maquina, 1=Operacion

// Process' variables
int temp_bus, tiempo_bus, hum_bus;  // copias de array_de_valores que se mantendran fijas hasta el final del proceso
int reloj = 0;                      // tiempo transcurrido en minutos desde que comenzo el proceso
int reloj_prev;
unsigned long reloj_milis;          // tiempo transcurrido en milisegundos desde que comenzo el proceso
unsigned long inicio_milis;         // milisegundos al comienzo de la operacion
int tiempo_restante;
bool resistencia_en_funcionamiento = false; // estado actual de la resistencia (por defecto, apagada)

// Phisical components
LiquidCrystal lcd(6,7, 2,3,4,5);
MAX6675 sensor_temp(16,15,14);
#define RELE 13
  // botones
#define AUMENTAR 8 // Aumentar valor
#define DISMINUIR 9 // Disminuir valor
#define SIGUIENTE 10 // Cambiar valor
bool sig_pres = false;
#define INI_DET 11 // Iniciar o Detener maquina
bool ini_det_pres = false;

//
// FUNCTIONS
//

// Funciones para control de lcd
void actualizarLCD() {
  if (!maquina_en_funcionamiento) { // si la maquina no esta en funcionamiento
    switch (valor_seleccionado){
      case 0: // temperatura
        lcd.home();
        lcd.print("»TEMP TIEMPO HUM");
        lcd.setCursor(5,1);
        lcd.print(array_de_valores[0]);
        lcd.setCursor(8,1);
        lcd.print("°C");
        break;
      case 1: // tiempo
        lcd.home();
        lcd.print(" TEMP»TIEMPO HUM");
        lcd.setCursor(5,1);
        lcd.print(array_de_valores[1]);
        lcd.setCursor(8,1);
        lcd.print("min");
        break;
      case 2: // humedad
        lcd.home();
        lcd.print(" TEMP TIEMPO»HUM");
        lcd.setCursor(5,1);
        lcd.print(array_de_valores[2]);
        lcd.setCursor(8,1);
        lcd.print("%");
        break;
    }
  }
  else { // si la maquina esta en funcionamiento
    switch (opcion_seleccionada){
      case 0:
        lcd.home();
        lcd.print("»MAQUINA  OPERAC");
        lcd.setCursor(0,1);
        lcd.print("TEMP");
        lcd.setCursor(5,1);
        lcd.print(temperatura);
        lcd.setCursor(9,1);
        lcd.print("TIE");
        lcd.setCursor(13,1);
        lcd.print(tiempo_restante);
        break;
      case 1:
        lcd.home();
        lcd.print(" MAQUINA »OPERAC");
        lcd.setCursor(0,1);
        lcd.print("TEMP");
        lcd.setCursor(5,1);
        lcd.print(temp_bus);
        lcd.setCursor(9,1);
        lcd.print("TIE");
        lcd.setCursor(13,1);
        lcd.print(tiempo_bus);
        break;
    }
  }
}

// Funciones de variables editables por el usuario
void aumentarValor(int cantidad) {
  array_de_valores[valor_seleccionado] += cantidad;
  actualizarLCD();
}
void cambiarValor(){
  switch (valor_seleccionado){
    case 0:
      valor_seleccionado = 1;
      break;
    case 1:
      valor_seleccionado = 2;
      break;
    case 2:
      valor_seleccionado = 0;
      break;
  }
  actualizarLCD();
}

// Funciones de control de proceso
void iniciarResistencia() {
  digitalWrite(RELE, HIGH);
  resistencia_en_funcionamiento = true;
}
void detenerResistencia() {
  digitalWrite(RELE, LOW);
  resistencia_en_funcionamiento = false;
}

void iniciarProc() {
  // realizar una copia de los valores en array_de_valores
  temp_bus = array_de_valores[0];
  tiempo_bus = array_de_valores[1];
  inicio_milis = millis();

  // iniciar la maquina (cuando continue el ciclo)
  maquina_en_funcionamiento = true;

  actualizarLCD();
}
void detenerProc() {
  detenerResistencia();

  // borrar variables
  temp_bus = 0;
  tiempo_bus = 0;
  reloj_prev = 0;
  reloj_milis = 0;
  inicio_milis = 0;
  tiempo_restante = 0;

  maquina_en_funcionamiento = false;

  actualizarLCD();
}

//
// MAIN PROGRAM
//

void setup() {
  // codigo que se ejecuta una unica vez:
  Serial.begin(9600);
  Serial.println("INICIANDO PROGRAMA");

  // relay
  pinMode(RELE, OUTPUT);
  detenerResistencia();

  // buttons
  pinMode(AUMENTAR, INPUT);
  pinMode(DISMINUIR, INPUT);
  pinMode(SIGUIENTE, INPUT);
  pinMode(INI_DET, INPUT);

  //iniciar lcd
  lcd.begin(16,2);
  actualizarLCD();
}

void loop() { // codigo que se ejecuta en bucle:
  // buttons
  if (digitalRead(AUMENTAR) == HIGH) { // if button AUMENTAR is pressed
    if (!maquina_en_funcionamiento) {  // and the machine is not working
      aumentarValor(5);                // increase the value
      delay(500);                      // and wait
    }
  }
  else if (digitalRead(DISMINUIR) == HIGH) { // si se presiona el boton DISMINUIR
    if (!maquina_en_funcionamiento) {        // IDEM AUMENTAR
      aumentarValor(-5);
      delay(500);
    }
  }
  else if (digitalRead(SIGUIENTE) == HIGH) { // si se presiona el boton SIGUIENTE
    if (!sig_pres) {                         // verificar si no se lo presiono antes
      sig_pres = true;                       // poner la var sig_pres en true para bloquear el boton
      cambiarValor();                        // y cambiar la variable
    }
  }
  else if (digitalRead(INI_DET) == HIGH) {   // si se presiona el boton INI_DET
    if (!ini_det_pres) {                     // verificar si no se lo presiono antes
      ini_det_pres = true;                   // poner la var ini_det_pres en true para bloquear el boton
      if (!maquina_en_funcionamiento) {
        iniciarProc();
      }
      else {
        detenerProc();
      }
    }
  }

  if (digitalRead(SIGUIENTE) == LOW) {    // si el boton SIGUIENTE no esta siendo presionado
    if (sig_pres) {
      sig_pres = false;                   // desbloquear el boton
    }
  }
  if (digitalRead(INI_DET) == LOW) { // si el boton INI_DET no esta siendo presionado
    if (ini_det_pres) {
      ini_det_pres = false;               // desbloquear el boton
    }
  }

  // Some output of data to the Serial monitor
  Serial.print("Valor seleccionado: ");
  Serial.println(valor_seleccionado);
  Serial.print(array_de_valores[0]);
  Serial.print(", ");
  Serial.println(array_de_valores[1]);
  Serial.print("Maquina en funcionamiento: ");
  Serial.println(maquina_en_funcionamiento);

  // PROCESS CONTROL
  if(maquina_en_funcionamiento) {

    // TEMPERATURE CONTROL
    temperatura_prev = temperatura;
    temperatura = sensor_temp.readCelsius();

    if (temperatura >= temp_bus) { // si la temperatura es igual o exede la deseada
      detenerResistencia(); // apagar la resistencia
    }
    else { // si la temperatura es menor que la deseada
      if (!resistencia_en_funcionamiento) { // y la resistencia esta apagada
        iniciarResistencia();
      }
    }

    if (temperatura_prev != temperatura) {
      actualizarLCD();
    }

    // TIME CONTROL
    unsigned long milis_ahora = millis();
    milis_ahora -= inicio_milis;
    if ( (milis_ahora - reloj_milis) >= 1000){
      reloj_milis = reloj_milis + 1000;
    }

    reloj_prev = reloj;
    reloj = reloj_milis/60000;

    tiempo_restante = tiempo_bus - reloj;
    /*
    Serial.print("Reloj de milisegundos=");
    Serial.println(reloj_milis);
    Serial.print("Reloj=");
    Serial.println(reloj);
    Serial.print("Tiempo restante=");
    Serial.println(tiempo_restante);
    */
    if (reloj >= tiempo_bus) { // si se llego al tiempo deseado
      detenerProc(); // detener
    }

    if (reloj_prev != reloj) {
      actualizarLCD();
    }

  }
}

Thanks in advance.

Have you tried powering through the USB jack? And can you try the Blink sketch from the Arduino IDE? If that sketch works, there must be something wrong with the code, in which case you need to add it to your question.

if you read your post carefully, you will find out that you used a lot of words to say nothing more than that you have an arduino nano powered by a phone charger, running some unknown code, and that you think that the code execution is affected when you touch the arduino .... first thing that you need to do is to verify that you actually are affecting the program execution and not affecting the LEDs only

@chrisl The USB jack has the same problem, it only works when its connected to the PC. The Blink sketch works fine. I'll add the code to the post.

@jsotola The execution is definetly getting affected, it runs slower than it should.

You can check this link https://store.arduino.cc/usa/arduino-uno-rev3. Open Documentation tab. 5V.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

@AmitRay so I should be powering the arduino through the Vin pin with a power supply higher than 7V?

@FacundoBarrera Yes that may solve this problem. Did you try that?

@AmitRay I did try, but was the same. Though I know now what is happening, the phone charger is making some noise that is interfiering with the arduino, and when I touch ground it discharges on me. I'll post that as the answer when I clarify some doubts that I have. Thank you for helping!

This stops when I touch ground with my finger or when the arduino is
  connected via USB to a computer.

It sure sounds like a grounding problem, probably between the PC and the Arduino. Try connecting the Arduino ground and the PC ground - my guess is that the problem goes away.
All of the electrical components in a system need to share the same ground for any communication to take place. It sounds like one of them might not.
Is either the PC or the charger plugged into the wall with an adapter that only carries two of the three wires? Usually each one will connect to ground side of the house circuit but if one of them doesn't ...

When the arduino is connected to the computer works as expected, but I can't depend on the computer like this. And I don't know what you mean with two or three wires, there are only two wires (5v and ground).

JRobert, did you read the question? or event the part you quote?


text:
6 channel PWM with 2 - 5 kHz frequency
Is it possible to set all 6 PWM frequencies to a value between 2 and 5 kHz?
I've read that the base frequency for pins pins 5 and 6 is 62500 Hz.
And the divisors for the pins 5 and 6 are only this ones: 1, 8, 64, 256, and 1024.
The closest I can get is 7.812,5 Hz with the 8 divisor. Are there any other possibilities to achieve this?

To be honest, I don't know. I haven't choosed yet. My first attempt was to do it with the Raspberry, but the suggestion was to use Arduino. So I found this example: https://playground.arduino.cc/Code/PwmFrequency/

So I know it's goin to be an Arduino, but not exactly which model, because I didn't knew which are capable of my requirements in my question. If this sooo unclear to you, then go on and vote.

ok, since you are talking about arduino for sure, I am removing the vote to close

Judging from your mentioning 62.5 kHz as the base frequency for
pins 5 and 6, I assume you are talking about an Arduino Uno or
something similar.
If you set the timer 0 to phase correct PWM mode (which is how the
Arduino core configures the other timers), then its base frequency is
about 31.373 kHz (F_CPU/510). With the prescaler set
to 8, you get a PWM frequency of about 3.922 kHz on pins
5 and 6.
Note that you can set all three timers in this mode and have 6 PWM
channels at this frequency. But note also that by reconfiguring
Timer 0 you loose all the standard Arduino timing functions.

Thank you for your answer. Are there any other models which are better suited for this? But nevertheless, this is quite helpfull. Thank You!

@WaKai: A Mega has way more timers. On the other hand, if you don't need the Arduino timing functions, the Uno could do the job fine, and the Mega would be overkill.

Ah, I see. Clock speed: 16 MHz divided by 510 in phase correct mode for the ~32 kHz base frequency. Neat :-)
As far I can think ahead, I won't need any more timers. So the UNO should be perfect.


text:
Is it possible to output a variable clock using Fast PWM?
I am trying output a clock and change its frequency dynamically with a rotary encoder.
When the code for the rotary encoder is included the clock doesn't reach its max freq(31Khz). But without the rotary encoder code, it does. What is happening that it can't reach its max freq?
const byte CLOCKOUT = 9;
int val;
int encoder0PinA = 3;
int encoder0PinB = 4;
int encoder0Pos = 0;
int encoder0PinALast = LOW;
int n = LOW;

void setup() {
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS12);   // CTC, no prescaling
  OCR1A =  0;

  pinMode (encoder0PinA, INPUT);
  pinMode (encoder0PinB, INPUT);
  Serial.begin (9600);
}

void loop() {
  n = digitalRead(encoder0PinA);
  if ((encoder0PinALast == LOW) && (n == HIGH)) {
    if (digitalRead(encoder0PinB) == LOW) {
      OCR1A-=100;
    } else {
      OCR1A+=100;
    }
    Serial.print (OCR1A);
    Serial.print ("/");
  }
  encoder0PinALast = n;
}

The Code that reaches the Max freq properly is below
void setup ()
  {
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS12);   // CTC, no prescaling
  OCR1A =  0;
  }

void loop (){
  }

you exclude a lot of values if you increment by 100 .... please post the code that reaches max freq

Note that when OCR1A-=100; makes TCNT1 lower than OCR1A you miss the compare match and have to wait a full second for the timer to overflow. Use waveform generation mode 15 instead of 4 (CTC) to avoid this.

Okay, I updated with the code that reaches the full freq. I intend to skip a lot of values in the increment as I am not trying to get every single value.
What does the changing to wave generation mode 15 do?

I'm not sure whether this is the real issue you have, but I spot an issue which can be the issue you have.
You wrote something like this:
if (pulseFromEncoder)
  if (direction1)
    OCR1A -= 100;
  else
    OCR1A += 100;

Now, the OCR1A is a unsigned 16 bit integer. A value of 100 corresponds to 1.6ms of delay on the timer (see comment from Edgar Bonet below). This is what happens when you rotate in direction 2:
        OCR1A  Time delay
Rotate:   300      4.8ms
Rotate:   200      3.2ms
Rotate:   100      1.6ms
Rotate:     0      0ms
Rotate: 65436   1047ms

See? The value rolls over and the time completely changes.
Now, maybe the issues are other (for instance changing the mode to 15 instead of 4 like EdgarBonet said (no idea on what this means, you should double check the differences on the atmega datasheet), but I strongly suggest you to fix this issue, for instance this way:
const uint16_t OCR1A_Min = 0
const uint16_t OCR1A_Max = 20000
const uint16_t OCR1A_Step = 100

...

if (pulseFromEncoder)
  if (direction1)
  {
    if (OCR1A > OCR1A_Min + OCR1A_Step)
      OCR1A -= OCR1A_Step;
    else
      OCR1A = OCR1A_Min;
  }
  else
  {
    if (OCR1A < OCR1A_Max - OCR1A_Step)
      OCR1A += OCR1A_Step;
    else
      OCR1A = OCR1A_Max;
  }

Sidenote: doesn't your encoder need debounce?

Re “let's assume the OCR1A is a unsigned 16 bit integer”: This is indeed the case. Re “Let's assume also that 100 corresponds to 1ms of delay”: It's actually 100 × 256 ÷ F_CPU = 1.6 ms.

@EdgarBonet Thank you, I updated the answer with your confirmations and fixed the data. As a side note, I was pretty close even if I gave a totally random value ;)

PWM doesn't vary frequency. It holds the frequency steady and varies the duty cycle of the output. (Percent of on-time to total time.) So unless fast Arduino PWM does something very unconventional, the answer to the question you asked is no.


text:
"variable does not name a type
Hey guys I'm getting an error that is im pretty sure to do with how i am initializing my variables. It is:
exit status 1
'threshold' does not name a type
Here's my code:
//Global Variables for moving max:

int analogValues[100];
int ir=0;
int maxA0=0;
int threshold = 0;
//Global variables for moving max ^^

//Global Variables for moving average ECG:
const int no_averages = 2;

unsigned long time = 0, peak1 = 0, peak2 = 0;
int binaryrange, bpm, i=0; //not sure what i does tbh
int readings[no_averages]; // the readings from the analog input
int readIndex = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average which we will display as ECG

void setup() {
// initialize serial communication with computer:
Serial.begin(115200);
// initialize all the readings to 0:
for (int thisReading = 0; thisReading < no_averages; thisReading++) {
readings[thisReading] = 0;
}

//set moving max shit to zero
  for (int is = 0; is < 100; is++) {
analogValues[is]=0;
  }
}

void loop() {
  //int maxA0=0; //Whether I intitate the variables here or globally, same error
  //int threshold = 0;
time = millis();

average=0;
readings[readIndex] = analogRead(A0);
readIndex++;
for (int ir=0; ir < no_averages; ir++) {
  average = average + readings[ir];
}
if (readIndex >= no_averages) {    // ...wrap around to the beginning of array if it has hit the end:
readIndex = 0;
}
average = average/no_averages;
if (average>1000) {
  average = 600;
}
Serial.print(average);

analogValues[ir]=average;
ir++;
if (ir>=100) {
  ir=0; } //This is to roll back to the start of the array if it surpasses the 100th array spot
for (int is = 0; is < 100; is++) {
 if (analogValues[is]>analogValues[is-1])
 analogValues[is]=maxA0;
  }
}

//**************************

//This line with error:

threshold=maxA0-40;

//**************************

if (average<threshold){
  binaryrange=0; }
if (average>threshold && binaryrange==0){
  peak1=peak2;
  peak2=time;
  bpm=60000/(peak2-peak1);
  binaryrange=1;
  }
   Serial.print(" ");
  Serial.println(bpm);
//BPM code ^^

delay(8); // delay in between reads for stability
i++;
}

THANKS!

"The line with the error" falls outside of any functions. In C and C++ we write executable code inside functions. You placed your
threshold=maxA0-40;

(and everything that follows) outside of any functions. Hence the error.
Errors like this are typically cased by improper placement of { and } braces. But this is something you have learn to check for yourself. Most C or C++ oriented code editors can usually help you with this. And proper code formatting can help you with this too. What you have now is such a mess, that a simple error is virtually impossible to see.

Ah man that is embarrasing, just had a rogue "}" in there that ruined my code. Thanks!

@glebecreator That's why is coding style and indentation so important. And even if you can't follow it, you can use Ctrl+T keystroke in Arduino IDE to reformat your code. If you try it, you'll spot part of code somehow misaligned.


text:
Two rpm counters with interrupts
Can I use two interrupts on to count rpm square signals coming from two hall effect sensor modules (that has built in comparators to generate square signals) ?
What if two signals come together ? Will they conflict with each other ?
Will this work on attiny85 ?
I used to use two interrupt to read encoders where the two signals never conflict with each other
Thank you in advance

What maximum frequency do the square waves have? If you really cannot risk to loose any edge of the signals, you can use them as clock input for the 2 timers of the ATTiny

Thank you for your comment chrisl ...I have 40 Hz as maximum input, but actually I work with arduino programing language so I didn't get the idea of using 2 timers ...

Oh, during writing an answer, I found, that only 1 of the two timers has an counter input pin, so that will not work on the ATtiny85. I will add that do my anser.

You can use INT0 and PCINT. The hardware will handle the checking of the signal, and will set a flag. When any of these flags are set the CPU will call the ISR. If both signals happen at the same time, both flags will be set, and the CPU will call their ISRs, one after the other. You won't loose any signals, unless the ISR takes more time, than the time between signals. The only slight problem is that the ISR isn't necessarily called at the exact time of the event.

There is more than 1 option how this can be done. A frequency of 40Hz is relatively slow, so you are not limited by this.
In my comment I first suggested to use the Timers/Counters with the signal as input, but I found, that this is only possible with one of the two timers of the ATtiny. Despite that, I will add this to the answer for information (and because this can be possible on other boards with more timer input pins).

Using the PinChange interrupt and doing counting in software: Since the ATtiny85 has only 1 external interrupt, you have to use the PinChange interrupt for this. If activated, this interrupt will trigger, when ever one of the pins 0 to 5 changes it's value. You can mask away any pin in this range, so that it doesn't count. You would use 2 pins and mask the others away. In the interrupt routine you would check the state of the two pins and increment the respective counter:
volatile unsigned int counter1=0;
volatile unsigned int counter2=0;

ISR(PCINT0){
    if(digitalRead(input_pin_1)) counter1++;
    if(digitalRead(input_pin_2)) counter2++;
}

(Note the volatile declaration of the variables, because they change inside of an ISR). The counterX variables can then read in defined time intervals (for example very second) to calculate the RPM. Of course, executing code in an ISR can mean, that you miss another interrupt. During the short time period between the first interrupt and the completed execution of the ISR no other PinChange interrupt will get registered. If that is a problem is dependend on how often the pulses will be inside this small range. If that only happens very rarely you can ignore that, since it introduces only very small errors. You can even make the ISR faster by not using digitalRead(), which takes a bit to execute, but using direct Prt Manipulations. That makes the error more unlikely.
The interrupts have to be configured for this, so you need a setup code like this (this will use direct manipulation of the status registers of the ATtiny):
PCMSK = 0b000110; // Mask all pins for this interrupt,except for PCINT1 and PCINT2
GIFR &= ~(1 << PCIF); //Clear PinChange interrupt flag
GIMSK |= (1 << PCIE); //Enable PinChange interrupt

In the loop function you can use the non-blocking code style from the BlinkWithoutDelay example, to regularly calculate the RPM from the counter values;
void loop(){
    if(millis()-timestamp > INTERVAL){
        GIMSK &= ~(1 << PCIE); //Disable PinChange Interrupt, so that we don't get interrupted by ti
        unsigned int countervalue1 = counter1;
        unsigned int countervalue2 = counter2;
        counter1=0;
        counter2=0;
        IMSK |= (1 << PCIE); //Reenable PinChange interrupt
        // Do the calcuation here with countervalueX and show the result somewhere
    }
}

It is important to disable the corresponding interrupt, when you are accessing the counterX variables, because you have to prevent them from changing midway during processing. To keep this short, they are just copied to local variables and then released again.

Attention: the following suggestion doesn't work on an ATtiny85, since it only has 1 timer input pin.

Using both available Timers/Counters and the signals as clock input: If you really don't want to miss any pulses, you can utilize two Timers/Counters. Timers and Counters are the same. A counter increments a status register on every falling or rising edge (depending on the configuration) of a signal. If this signal is derivated from the chips clock, this is called a Timer. You would use it as a Counter, feeding each square wave to one Counter input pin. To actually get the RPM, you can either check the counters value (TCNT0) after defined time interval, or you can activate the overflow interrupt of both timers and measure the time between the overflows.
Since here the edge-sensing is done in hardware, no pulse can be missed. On the other side, this way needs more configuring and blocks 2 precious timers.

When working with the status registers in such a direct way, the datasheet of the ATtiny85 is a must read.

Ok I think using an Arduino pro mini will be cheap enough if I want to use the second method (the two timers method ) and it will be accurate ... What do you think if I want to add i2c or serial to the code ?

That shouldn't be a problem with the Pro mini, since it has hardware serial and hardware I2C. The ATtiny not, so the Pro mini really would be the better board.

If I use two interrupts will this conflict with arduino code (like if I have three loadcells that I need to read or write a value to a servo ) ?? .. my original post was about using an attiny85 (or atmega328 in arduino pro mini ) to send rpm values to a master arduino that will gather all values and make some dicitions ..

As I remember the servo library uses Timer1 and Timer 0 is normally used for the Arduino timing functions (delay, millis and siblings). To also use that a slave Arduino to read the rpm might be good. Or a bigger Arduino with more timers

If you can skip using interrupts, your Tiny could still do the job and not miss any pulses, as long as loop() can be executed at >40Hz, and the pulses are not be extremely short "spikes" but have a reasonable duty-cycle (or if short, you can sample faster):
// Pin data
static struct {
   uint8_t pinNum;
   bool wasHi;       // last state
   unsigned count;   // pulse count
} pinsDat[2] = {
   {input_pin_1, false, 0},
   {input_pin_2, false, 0},
};

void setup(){
   ; // your setup here
}

void loop(){
   countPulses();
   // ...
}

void countPulses(){
   for( uint8_t i = 0; i < 2; ++i){
      if( !digitalRead(pinsDat[i].pinNum) )
         isHigh1 = false;       // pin lo, just save its state
      else if( !pinsDat[i].wasHi ){
         ++pinsDat[i].count;    // pin hi; count it
         ++pinsDat[i].wasHi;    // save its state
      }
   }
}


text:
Using MPU-6050 without I2C
My target is to use multiple MPU-6050 at once, I searched on the internet and found that they can be hooked up really simply. Just connect in parallel and use I2C-Scanner. Then get those addresses and use normally.
But I can't find another address, there appears to be just one address 0x68, that is the reason why, I want to connect my other MPU-6050 in other pins.
How this can be achieved ?

The MPU-6050 has 1 pin to change 1 bit of the address. Means, that you can connect 2 MPU-6050 to the same I2C bus.

How, can you describe ?? Please

from datasheet "the address of the one of the devices should be b1101000 (pin AD0 is logic low) and the address of the other should be b1101001 (pin AD0 is logic high)"

As you can read in the MPU-6050's datasheet, it uses the I2C address 0b110100X, where X is the state of the pin AD0. If you wire AD0 to ground, the address will be 0b1101000, whereas if you wire it to Vcc it will be 0b1101001. That is equivalent to the addresses 0x68 and 0x69.
That means, that - depending on how you wire AD0 - you can have 2 distinct MPU-6050's on the same I2C bus (you cannot have devices with the same address).
If you really need to connect more than 2 of them, you have to use an I2C multiplexer like PCA9544A, which will divide the bus down to sub-busses.

EDIT: Usually the address pins of I2C devices are set permanently by wiring them either to ground or Vcc. The sense of the address system is, that a slave device will stay at it's address, not changing it. But as Jot reported in the comments and as the Arduino Playground site of the MPU-6050 confirms, you can actually set the address pin of the MPU-6050 during operation.
You need 1 digital output pin on your Uno for each MPU, which then get's tied to the MPU's AD0 pin via a voltage divider. The last part is important: You need a voltage divider, because the MPU is a 3.3V device, while the Uno works with 5V. To avoid frying the address pin, you need to step down the voltage.
Then you would use the address pins to set all MPU's to one address (let's say 0x69). When you need to communicate with one of them, you toggle it's address pin, which will change it's address (in this case to 0x68). Then you can use the normal I2C workflow with this address (0x68). When you are done, you can put this MPU back to the other address by again toggling the address pin. You can repeat this with any of the connected MPU's, which can be many (I think the limit here is the I2C bus itself with it's wires capacity).
This is a workaround and not really, what the I2C bus is meant for. But it seems to be valid solution. Just be sure, that the addresses, that you communicate with, are always unique. Contacting an address, which belongs to more than 1 device, will block your I2C bus.

It means, using a loop toggling value of AD0, I can access both ?

I don't think, that the MPU continously checks AD0, but that it checks it at power on. (Though I didn't found that clearly in the datasheet) That means, that you cannot change the address without power cycling the MPU. Either way, you won't be able to address more than 2 MPU's on the same bus.

@chrisl I have read somewhere that AD0 is used runtime. It is possible to have many mpu6050 sensors and select them one by one via its AD0 pin (keep them at 0x69 and use one at 0x68). This can not be done with an arduino uno, since a pin with 5v would blow the mpu6050 via the AD0 pin.

@Jot Can you maybe remember, where you read that? Would be good to have some reference for that.

For example here: https://forum.arduino.cc/index.php?topic=545257.msg3716437#msg3716437 I have not tested it myself.

This solution is also being reported as working at the Arduino Playground site of the MPU-6050. I will add that to my answer tomorrow.

You can connect more than 2 in serial by using the Address bit like a chip select.
Say you had 8 of them. Use a shift register with the 8 outputs going to the 8 chips. Now output 0b00000001 and use I2C address 0x69, only the one device with a 1 on its address line will reply. Then use 0b00000010 for the 2nd device, 0b00000100 for the 3d, etc. up to 0b10000000 for the 8th.


text:
BLE splitting string data
I am working with BLE 4.2 (ESP32) that sends IMU (accel, gyro, mag) data to my mobile app (Android). Unfortunately, I can send only 20 bytes in one packet.
This is the code I have: (I am connecting the float raw data (ax, ay,...my, mz...etc) read from the accelerometer.)
char myConcatenation[20];
char myStr[","];
.
.
.
 sprintf(myConcatenation,"%3.2f%s%3.2f%s%3.2f%s%3.2f%s%3.2f%s%3.2f%s%3.2f%s%3.2f%s%3.2f%s%3.2f%s%3.2f%s%3.2f", ax, myStr, ay, myStr, az, myStr,gx,myStr, gy, myStr, gz, myStr, mx, myStr, my, myStr, mz, myStr, yaw, myStr, pitch, myStr, roll);
.
.
.
pCharacteristic->setValue(myConcatenation);

pCharacteristic->notify(); // Send the value to the app!

Do you know how to construct a code so I would notify the app with new data of 20 Byte length? For example, each packet constructed of every sensor reading:
1. (ax, ay, az)
2. (gx, gy, gz)
3. (mx, my, mz)
4. (yaw, pitch, roll)

Thank you for any advice and patience with my poor programming skills.

How is this related to arduino?

I am using Arduino IDE and I didn't know where else to put this. Sorry if it doesn't fit the thread topic.


text:
Connect MPU6050 in pins other than A4 & A5
I need to use a MPU6050 gyro and a Ultrasonic sensor for my project. My Arduino Uno did not come with separate SDA and SCL pins, so I have to use the A4 and A5 pins for that purpose, and I have connected the Ultrasonic sensor with them.
\With no SDA and SCL pins available, and A4 and A5 already occupied, is there any way to use other pins like A0 and A1 for SDA and SCL connections?

Have you seen the software I2C library here?

Why not move the ultrasonic to other pins? BTW: SCL/SDA and A4/A5 are physically the same pins - you can't use both at once.

A4/A5 are the I2C Bus. You will connect multiple I2C devices in parallel to the pins. I would suggest wiring them Uno to device to device, with pullup resistors 3.3K or 4.7K pullup resistors to Vcc on the last device.

Your Uno did not come with seperate SDA and SCL pins, because on the microcontroller, that is used on the Uno (Atmega328p) these pins are shared too. That is a common practice, because not everyone needs I2C, but may want more analog pins.
You have basically 2 ways to go here:

You can leave the ultrasonic sensor, where it is connected now, and try it with a software I2C library like this one, that can be used on nearly any other pin pair. Note, that in this case the I2C protocol will be completely handled in software, which puts a bigger workload on the microcontroller and may need other resources, that you want to use later (for example it might use timer hardware).
You can put the ultrasonic sensor to other pins, because it is not limited anyway. You can use any digital pin pair. The MPU can then be connected to A4 and A5, as they are the pins of the hardware I2C interface. IMO this is the cleaner solution, since the core of the I2C protocol will be handled in hardware without the code doing anything for it. The code just puts the data into a buffer, not more. Also it will not use any other hardware inside of the microcontroller.

Which of these options is the best here is up to you. Maybe you have a good reason to not move the ultrasonic sensor to other pins.

Uh oops: The LCD with I2C is connected to the A4 and A5, not the ultrasonic sensor. So I guess I'll have to go with the first one?

You can connect multiple devices to the same I2C bus. It is a bus and every device has an address.


text:
Help Troubleshooting L298n connected to dc motor
I am relatively new to Arduino, and I am trying to power a DC motor with the L298N dual H-Bridge. I have done as follows:
I am powering everything with the Arduino that is connected to the PC. (I know this isn't ideal, but I don't have a better power supply yet)
I connected the 5V output from Arduino to the 12V terminal of the L298N, and connected it to the Arduino ground. The red light from the L298N shines brightly.
Then, I connected the IN3 and IN4 pins to the Arduino digital pins 7 and 8, respectively.
Finally, I connected the Out 3 and Out 4 to my DC motor, but it doesn't turn at all. I use the following code:

int In3=7;
int In4=8; //idem para In2

void setup() {
  pinMode(In3,OUTPUT); //avisa que nuestros pines son todos outputs
  pinMode(In4,OUTPUT);

  digitalWrite(In3,HIGH);
  digitalWrite(In4,LOW);
}

void loop() {

}

For the time being I decided to not use the PWM, so that I can start simple. I tried changing all cables and even the motor, but it just won't rotate. The L298N is brand new, so it's unlikely that it is damaged. What could I try next?

Welcome to Arduino! Please take the tour and visit the helpcenter to see how things work here. Note that (SOLVED) tags should not be edited into the question's title, please "accept" the correct answer instead.

I realized that I had the jumper disconnected from the ENB pins, which immediately solved the problem when I reconnected it, so it is now fixed!

It's OK to accept your own answer as the solution to the problem. I think you get 15 rep for it.


text:
Troubleshooting WS2812B LED strip
I am doing a project for my master thesis and I have 6 stripes of WS2812B LEDs each one containing 77 LEDs. I finished the design and now want to turn them on.
I used an old power supply to power it, but now that I am running it, doesn't work. I checked the voltage with a multimeter and it shows that I have 5 volts and it seems doesn't have any problem but the data doesn't transfer to my strip.
I just copy past FastLED from libraries and changed the number of LEDs. I thought maybe I am using the Funduino from school, maybe this is a problem and I need another Arduino board?

Please show us a schematic or wiring diagram on the picture we cannot really see the connections. Have you tried to only connect 1 little strip for testing? And please show us your code (you can add it to your question by editing it. Don't forget to format it correctly by selecting it and clicking the {} button of the editor).

Since, in the photo, you are only testing with a very short strip of 4 leds, I'd suggest try powering the strip from the Arduino's 5V. Just to make sure that the code works. After that you can add the PC power supply.

Please show us your code

Are you completely sure that these are WS2812B LEDs? To read more, check out this great link from Core Electronics:
https://core-electronics.com.au/tutorials/addressable-rgb-led-controllers.html
It is more than likely your code. Download the code from a known working example and get that working. Try using an example program such as:

https://howtomechatronics.com/tutorials/arduino/how-to-control-ws2812b-individually-addressable-leds-using-arduino/
https://core-electronics.com.au/tutorials/ws2812-addressable-leds-arduino-quickstart-guide.html
https://learn.adafruit.com/adafruit-neopixel-uberguide/software

Once you have known working hardware then delve into your own code and find the problem.
Also check your wiring with fresh eyes. It could be something simple.


text:
Electret microphone board strange offset using Arduino
I'm experimenting with an electret microphone, specifically this one.  I put it on my scope and I see what I expect - a really small voltage, typically under 20mV, that varies appropriately with sound.
However, when I put it into my Arduino (connecting signal pin to A0, V to 5V, and G to GND) and read it using analogRead on the appropriate pin, I end up getting a strange offset.  The analog read should read 0 more or less constantly, due to the low voltage coming out of the board.  However, I get an offset of around 425 counts on the ADC, implying that the voltage is somewhere around 2.5V.
What's going on?  Why would the arduino be reading a voltage when there isn't any?

When you test it with a scope, what supply voltage are you using?

5V, from the Arduino 5V pin

An electret microphone is like a resistor which changes its value according to the sound.
To use it you must form a voltage divider with it, as if it were half of a potentiometer.
Thus you add a resistor to +5V (which is already on the board).  This means that when it is silent the voltage you get is the ratio of the resistor and the resistance of the microphone.
If the resistance has been chosen correctly then the output you get should be roughly half the supply voltage when silent. Any sound will cause that output to swing around that "zero" point.
It's just like a potentiometer.  When silent the potentiometer is in the central point. When you make noise you're moving the potentiometer in both directions.
To get rough values you should first get the "silent" reading from analogRead. You can then subtract that value from all subsequent readings.
Note that the results will be non-linear. To do it properly you should calculate the resistance of the microphone by using the supply voltage, the "upper" resistor value, and the sampled voltage to calculate the resistance value like you would for any other resistive sensor (such as an LDR or force sensitive resistor).

You're right.  I think something is wrong with my scope, then, because it showed the output centered around 0V.  Looking at it on a multimeter and it's at 2.5V when quiet.

Is your scope set to AC coupling?

It was set to DC coupling, but I think that something is wrong with that particular mode.  There is no difference between AC and DC coupling, leading me to believe that the coupling circuitry is not disengaging, causing my confusion above


text:
Arduino - Print file name
I need my sketch to print the name of the original INO file at the beginning of execution (during setup).
Is it possible?  If so, what is the resource which should be used?

You can use the macro __FILE__ to get the filename that is being compiled.  That may not be your INO file, but may be some derivative of it.
Serial.println(__FILE__);

You also get some other handy macros:
__DATE__
The date the sketch was compiled

__TIME__
The time the sketch was compiled

__LINE__
The line number where __LINE__ is being used

The combination of __FILE__ and __LINE__ is commonly used for debugging:
Serial.prinln("Error 23 at line " __LINE__ " of " __FILE__);


text:
How to use I2C library
My A4 and A5 pins are already hooked up to a LCD and I want to connect a MPU6050 as well. In a separate thread, someone told me to use SoftI2CMaster library to use other pins as SDA ans SCL. But I don't quite know how to do that. I want to use A2 and A3 for I2C, and a code snippet would be very helpful.

Are there no examples in the SoftI2CMaster library?

I tried following them, but got a lot of errors, a lot of them

in previous question it was ultrasonic sensor on A4 and A5. now it is LCD. has the LCD I2C interface? I2C is a bus. you can wire more I2C devices to the I2C pins

Yeah the LCD's got I2C. Tried wiring them like that, didn't work.

Oh and yeah, my bad. Wrote ultrasonic sensor by mistake : /

got a lot of errors, a lot of them ... are we supposed to guess what they were?

You really should use the hardware I2C bus on A4 and A5 for both devices. Describe exactly, how it didn't work when you tried. Provide a schematic or wiring diagram and show us your code. Then we will look, if we can spot the problem.

please post your code

Ya, I will jump on the bandwagon and say again that I2C is a bus, it is designed to handle multiple devices.  Work on getting it to work correctly rather then hoping that bitbanging it with software is going to work.

If you are not using PULL UP in your SCL SDA lines please use them as I2C lines are open drain by default.

Use both devices on I2C, with different addresses.  Hook it up like this

And call each transmission with a different address
void setup() {
  Wire.begin();                           //begin the wire comunication
  Wire.beginTransmission(0x68);

Image and snippet from electronoob's very complete tutorial


text:
Using a photo resistor to detect objects of a certain color
I am trying to build a robot that detects cubes of a certain color, and later picks them up.
I was planning to use a camera and process the image, but I was told that Arduino is not capable of image processing.
Now, I was thinking that I could maybe use a photoresistor that is enclosed by a green light filter sheet (so that only the light of a certain color can pass). Thus, if my robot is facing a cube of the color I want, the photoresistor should detect this.
Is this at all possible? I know how filters work in theory, but I have never used one before.
If not, is there another way to try to detect color using an Arduino?

Through a green filter, white, green and yellow look the same.

There are colors sensors like the TCS230 suggested below, but the object has to be near the sensor to work. They don't work for detecting the block more than a few centimeters away.

@Gerben that depends on the optics.  Coupled to a basic looking glass, these sensors could do the trick.

@Nick Heumann , dont forget to award the correct answer checkmark whenever you come to the conclusion that one answer is (the most) correct.  That will make it clear that you have ceased actively looking for a solution, since you havent posted a valid answer.  Cheers and welcome ;)

Use a TCS230 photo sensor and a 6500K light source to color correct your objects.

This hookup will get you started

This sketch, courtesy of Best-Microcontroller-Projects  will get you going.  Read the tutorial and dont forget to calibrate.
//
// Detect colors using TCS230.
//

// Arduino uno pins for control of TCS230
#define TCS320_OE 7
#define TCS320_S0 10
#define TCS320_S1 11
#define TCS320_S2 2
#define TCS320_S3 3
#define TCS320_OUT 4

#define variance 50  // Acceptable detection error 2%.

#define SEL_RED  \
   digitalWrite(TCS320_S2,LOW);digitalWrite(TCS320_S3,LOW)
#define SEL_GREEN \
   digitalWrite(TCS320_S2,HIGH);digitalWrite(TCS320_S3,HIGH)
#define SEL_BLUE \
   digitalWrite(TCS320_S2,LOW);digitalWrite(TCS320_S3,HIGH)
#define SEL_CLEAR \
   digitalWrite(TCS320_S2,HIGH);digitalWrite(TCS320_S3,LOW)

#define TWO_PER \
   digitalWrite(TCS320_S0,LOW);digitalWrite(TCS320_S1,HIGH);

#define debug(a) Serial.println((a));

#define NUMCOL 5

// int RGB[NUMCOL][3]; // Five colors with 3 elements.
// Array of NUMCOL strings len 10. 11 for null.
// char colname[NUMCOL][11];

// Typical values for 2% dividers (set variance to 50).
int RGB[NUMCOL][3]={
   {248,647,393},
   {188,261,265},
   {404,710,546},
   {506,493,304},
   {930,1199,837},
};

char colname[NUMCOL][11]={
"red",
"yellow",
"brown",
"blue",
"black",
};

////////////////////////////////////////////////////////////////
void setup() {

   pinMode(TCS320_OE,OUTPUT);
   pinMode(TCS320_S0,OUTPUT);
   pinMode(TCS320_S1,OUTPUT);
   pinMode(TCS320_S2,OUTPUT);
   pinMode(TCS320_S3,OUTPUT);
   pinMode(TCS320_OUT,INPUT);

   TWO_PER;

   digitalWrite(TCS320_OE,LOW); // On always.

   Serial.begin(115200);
   Serial.println("TCS230 color detector");
}

////////////////////////////////////////////////////////////////
unsigned long get_TCS230_reading(void) {
  unsigned long val;
  noInterrupts();
  val = pulseIn(TCS320_OUT,HIGH,20000); // 2000us=2ms  2Hz min.
  interrupts();
  return val;
}

static int clr,red,green,blue;

////////////////////////////////////////////////////////////////
uint16_t detect(void) {
   unsigned long val;

    SEL_RED;
    red = val = get_TCS230_reading();
    Serial.print("RED: "); Serial.print(val);

    SEL_GREEN;
    green = val = get_TCS230_reading();
    Serial.print(" GREEN: "); Serial.print(val);

    SEL_BLUE;
    blue = val = get_TCS230_reading();
    Serial.print(" BLUE: "); Serial.print(val);

    Serial.print(" \n");
}

////////////////////////////////////////////////////////////////
int withinEQ(int c, int xl, int xh) {
   if (c>=xl && c<=xh) return 1;
   return 0;
}

////////////////////////////////////////////////////////////////
// Compare a value to a value and variance.
int compare(int c, int v, int err) {
int xh=v+err, xl=v-err;
   if (withinEQ(c,xl,xh)) return 1;
   return 0;
}

////////////////////////////////////////////////////////////////
void loop() {
uint8_t chr,i,fnd;

   if (Serial.available()>0) {

      chr = Serial.read(); // Consume.

      // Find color match.
      detect();
      fnd=0;
      for (i=0;i<NUMCOL;i++) {
     if ( compare(red,RGB[i][0],variance) &&
          compare(green,RGB[i][1],variance) &&
          compare(blue,RGB[i][2],variance)
        ) { // Found
          Serial.print("Col is :");
          Serial.println(colname[i]);
          fnd=1;
          break;
        }
      }
      if (!fnd) Serial.println("NOT Found");
   }
}

Nice theory but since you're facing real-world conditions and not ideal ones, I think you'll have a hard time with this approach. I.e. your cube is likely not the same shade of green that your filter lets through. What about lighting - do you have a neutral white light source? I recommend you take a look at this Arduino RGB Sensing Tutorial using the TCS230 Colour Sensor for a headstart.


text:
Print unsigned long long in ESP8266
I need to print an unsigned long long variable:
unsigned long long t = 1559072327000ULL;
I have tried the following:
Serial.println(t); // call of overloaded 'println(uint64_t&)' is ambiguous

char[18] buf;

sprintf(dt, 18, "%lu", t); // Prints 4294165848

snprintf(dt, 18, "%lu", t); // Prints 126

vsnprintf(dt, 18, "%lu", t); // cannot convert 'uint64_t {aka long long unsigned int}' to '__gnuc_va_list {aka __va_list_tag}'

Any suggestion?

char[18] buf; <-- what on earth is this? When you intend to post code in your question, please don't fake the code. Post the real code you actually tried to use.

Okay, I figured out... this two prints the right number:
sprintf(dt,"%llu", t);
snprintf(dt, 18, "%llu", t);


text:
Can't open serial monitor on Ubuntu (Teensy 3.2)
I am running a simple blink/hello world program on Teensy 3.2. The code is compiling and running fine but I can't see the serial output. When I try to open the serial monitor it gives me

"Board at /sys/devices/pci0000:00/0000:00:14.0/usb3/3-1 is not
  available"

The source code is pasted in below, and the terminal outputs below that.
I'm using Teensyduino 1.4.6 and Arduino IDE 1.8.9 running on Ubuntu 18.04. The 49-teensy.rules file has been copied to /etc/udev/rules.d/ as required.
The Tools > Port menu is greyed out, can't select it.
Any suggestions on what I am doing wrong? Why can't I see the serial output?
int led = 13;

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

void loop() {
  digitalWrite(led, HIGH);
  Serial.println("Hello (on) world");
  delay(1000);
  digitalWrite(led, LOW);
  Serial.println("Hello (off) world");
  delay(1000);
}

Terminal output below:
> /usr/local/arduino/arduino-1.8.9/arduino-builder -dump-prefs
> -logger=machine -hardware /usr/local/arduino/arduino-1.8.9/hardware -tools /usr/local/arduino/arduino-1.8.9/tools-builder -tools /usr/local/arduino/arduino-1.8.9/hardware/tools/avr
> -built-in-libraries /usr/local/arduino/arduino-1.8.9/libraries -libraries /home/hubert/Arduino/libraries -fqbn=teensy:avr:teensy31:usb=serial,speed=48,opt=o2std,keys=en-us -ide-version=10809 -build-path /tmp/arduino_build_530222 -warnings=all -build-cache /tmp/arduino_cache_588473 -verbose /home/hubert/Arduino/Blink_T32/Blink_T32.ino
> /usr/local/arduino/arduino-1.8.9/arduino-builder -compile
> -logger=machine -hardware /usr/local/arduino/arduino-1.8.9/hardware -tools /usr/local/arduino/arduino-1.8.9/tools-builder -tools /usr/local/arduino/arduino-1.8.9/hardware/tools/avr
> -built-in-libraries /usr/local/arduino/arduino-1.8.9/libraries -libraries /home/hubert/Arduino/libraries -fqbn=teensy:avr:teensy31:usb=serial,speed=48,opt=o2std,keys=en-us -ide-version=10809 -build-path /tmp/arduino_build_530222 -warnings=all -build-cache /tmp/arduino_cache_588473 -verbose /home/hubert/Arduino/Blink_T32/Blink_T32.ino Using board 'teensy31'
> from platform in folder:
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/avr Using core
> 'teensy3' from platform in folder:
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/avr Detecting
> libraries used...
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-g++
> -E -CC -x c++ -w -g -Wall -ffunction-sections -fdata-sections -nostdlib -fno-exceptions -fpermissive -felide-constructors -std=gnu++14 -Wno-error=narrowing -fno-rtti -mthumb -mcpu=cortex-m4 -fsingle-precision-constant -D__MK20DX256__ -DTEENSYDUINO=146 -DARDUINO=10809 -DF_CPU=48000000 -DUSB_SERIAL -DLAYOUT_US_ENGLISH -I/usr/local/arduino/arduino-1.8.9/hardware/teensy/avr/cores/teensy3 /tmp/arduino_build_530222/sketch/Blink_T32.ino.cpp -o /dev/null
> Generating function prototypes...
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-g++
> -E -CC -x c++ -w -g -Wall -ffunction-sections -fdata-sections -nostdlib -fno-exceptions -fpermissive -felide-constructors -std=gnu++14 -Wno-error=narrowing -fno-rtti -mthumb -mcpu=cortex-m4 -fsingle-precision-constant -D__MK20DX256__ -DTEENSYDUINO=146 -DARDUINO=10809 -DF_CPU=48000000 -DUSB_SERIAL -DLAYOUT_US_ENGLISH -I/usr/local/arduino/arduino-1.8.9/hardware/teensy/avr/cores/teensy3 /tmp/arduino_build_530222/sketch/Blink_T32.ino.cpp -o
> /tmp/arduino_build_530222/preproc/ctags_target_for_gcc_minus_e.cpp
> /usr/local/arduino/arduino-1.8.9/tools-builder/ctags/5.8-arduino11/ctags
> -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives /tmp/arduino_build_530222/preproc/ctags_target_for_gcc_minus_e.cpp
> Compiling sketch...
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/precompile_helper
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/avr/cores/teensy3
> /tmp/arduino_build_530222
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-g++
> -x c++-header -O2 -g -Wall -ffunction-sections -fdata-sections -nostdlib -MMD -fno-exceptions -fpermissive -felide-constructors -std=gnu++14 -Wno-error=narrowing -fno-rtti -mthumb -mcpu=cortex-m4 -fsingle-precision-constant -D__MK20DX256__ -DTEENSYDUINO=146 -DARDUINO=10809 -DF_CPU=48000000 -DUSB_SERIAL -DLAYOUT_US_ENGLISH -I/usr/local/arduino/arduino-1.8.9/hardware/teensy/avr/cores/teensy3 /tmp/arduino_build_530222/pch/Arduino.h -o
> /tmp/arduino_build_530222/pch/Arduino.h.gch Using previously compiled
> file: /tmp/arduino_build_530222/pch/Arduino.h.gch
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-g++
> -c -O2 -g -Wall -ffunction-sections -fdata-sections -nostdlib -MMD -fno-exceptions -fpermissive -felide-constructors -std=gnu++14 -Wno-error=narrowing -fno-rtti -mthumb -mcpu=cortex-m4 -fsingle-precision-constant -D__MK20DX256__ -DTEENSYDUINO=146 -DARDUINO=10809 -DF_CPU=48000000 -DUSB_SERIAL -DLAYOUT_US_ENGLISH -I/tmp/arduino_build_530222/pch -I/usr/local/arduino/arduino-1.8.9/hardware/teensy/avr/cores/teensy3 /tmp/arduino_build_530222/sketch/Blink_T32.ino.cpp -o
> /tmp/arduino_build_530222/sketch/Blink_T32.ino.cpp.o Compiling
> libraries... Compiling core... Using precompiled core:
> /tmp/arduino_cache_588473/core/core_teensy_avr_teensy31_usb_serial,speed_48,opt_o2std,keys_en-us_d47a876dd1beb90b689e2017ddeb665b.a
> Linking everything together...
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-gcc
> -O2 -Wl,--gc-sections,--relax,--defsym=__rtc_localtime=1559084002 -T/usr/local/arduino/arduino-1.8.9/hardware/teensy/avr/cores/teensy3/mk20dx256.ld
> -lstdc++ -mthumb -mcpu=cortex-m4 -fsingle-precision-constant -o /tmp/arduino_build_530222/Blink_T32.ino.elf
> /tmp/arduino_build_530222/sketch/Blink_T32.ino.cpp.o
> /tmp/arduino_build_530222/../arduino_cache_588473/core/core_teensy_avr_teensy31_usb_serial,speed_48,opt_o2std,keys_en-us_d47a876dd1beb90b689e2017ddeb665b.a
> -L/tmp/arduino_build_530222 -larm_cortexM4l_math -lm /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-objcopy
> -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 /tmp/arduino_build_530222/Blink_T32.ino.elf
> /tmp/arduino_build_530222/Blink_T32.ino.eep
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-objcopy
> -O ihex -R .eeprom /tmp/arduino_build_530222/Blink_T32.ino.elf /tmp/arduino_build_530222/Blink_T32.ino.hex
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/stdout_redirect
> /tmp/arduino_build_530222/Blink_T32.ino.lst
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-objdump
> -d -S -C /tmp/arduino_build_530222/Blink_T32.ino.elf /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/stdout_redirect
> /tmp/arduino_build_530222/Blink_T32.ino.sym
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-objdump
> -t -C /tmp/arduino_build_530222/Blink_T32.ino.elf /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/teensy_post_compile
> -file=Blink_T32.ino -path=/tmp/arduino_build_530222 -tools=/usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/ -board=TEENSY31 Opening Teensy Loader... /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/arm/bin/arm-none-eabi-size
> -A /tmp/arduino_build_530222/Blink_T32.ino.elf Sketch uses 13468 bytes (5%) of program storage space. Maximum is 262144 bytes. Global
> variables use 4564 bytes (6%) of dynamic memory, leaving 60972 bytes
> for local variables. Maximum is 65536 bytes.
> /usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools/teensy_post_compile
> -file=Blink_T32.ino -path=/tmp/arduino_build_530222 -tools=/usr/local/arduino/arduino-1.8.9/hardware/teensy/../tools -board=TEENSY31 -reboot -port=/sys/devices/pci0000:00/0000:00:14.0/usb3/3-1 -portlabel=(null) -portprotocol=(null)
Board at /sys/devices/pci0000:00/0000:00:14.0/usb3/3-1 is not available

And if you select the actual /dev/ttyACM0 serial port and try again...?

Go into the Tools menu, then Port, and select the port.

Have you installed the "49-teensy.rules" file as described in the tutorial?

Have updated question: the Ports menu is greyed out and the "49-teensy.rules" is installed.

It looks like you haven't even managed to program the board - so there is no serial port for you to use.


text:
Controlling a 5m LED strip with a Nano or Uno
I'm wanting to control a 12V LED strip (5m, 60 LEDs per meter) with a Nano or Uno. I know from Adafruit that I'll need some power transistors but I'm not sure that I have the right type. I have 6 transistors labelled 30N06L, and I'm hoping they're equivalent to the ones used. Are mine ok to use, or do I need to buy others?

You have a lot of LEDs that you need to power so lets run through the calculations. Assuming that they are RGB LED strips, ie 3 LEDs per physical LED:
5 x 60 x 3 = 900 LEDs

Assuming each has a current draw of 20mA, that is (900 x 20mA) 18A of total current if all are on at the same time at full brightness.
Since each colour will be controlled by its own FET, each FET will be required to drive 6A at full brightness.
The FET that you have is a Fairchild FQP30N06L 60V LOGIC N-Channel MOSFET that can drive up to 32A. Of course, that would need a large heatsink at that current.
If you plan to have any of the colours on at full brightness for extended periods I would recommend putting a heat sink on the tab to help dissipate the heat.
The Arduino Uno/Nano uses a 328P microcontroller at 5V which, according to the datasheet, is suitable to drive the FET.
These FETs should do the job.

I'd add that the wiring for the strips should be carefully chosen, since letting 18A pass through a single piece of strip will cause problems... Moreover how could you say that they are RGB LEDs? They can also be white 5050, and so 18A will need to pass through the same transistor...

The assumption of RGB came from the Adafruit link in the OP's question. I could be wrong.

Please also note that I am assuming 20mA per LED. The calculations will change depending on the current draw of each LED.


text:
What type of Arduino to buy
I am doing a project for school to run 462 LEDs in 6 series (77 each) and a stepper motor altogether, I wanna know what model of Arduino I should buy (not so expensive)?
I am using individually addressable WS2812B RGB LED strips ...
So it should be controlled in 6 groups of 77 LEDs in each group.

Are the LEDs build into a strip or just simple LEDs? If the former: What type of strip/LEDs to you have? Should every LED be controlled individually or together in groups?

Can you give more details. It is hard to recommend a board with so little details.

With these requirements you can use most available Arduinos. The WS2812 LED strips need 1 pin per strip (or 1 pin in total, if you daisy-chain all the strips, meaning connecting the data lines of them to one big strip). How many pins you need for the stepper motor depends on the type of motor and what type of driver you have for it. Most stepper drivers need 2 digital pins from your Arduino (1 direction pin and 1 pulse pin). There are also cheap drivers based on the ULN2003 chip, where you have to control the phases directly, needing 4 pins.
You should also buy an Arduino, that leaves you a big headroom to develop your project further, if you want.
An Arduino Uno or Nano would be good fitting for this project (though smaller Arduinos like the Pro Micro also would work). If you are able to order them over sites like Aliexpress directly from china (and if you are ok with a longer shipping time), you can get Nanos for 1 - 2$.

Since you have many LEDs, you really have to consider your power supply. 462 LEDs, which need up to 60mA each (20mA for each colour in full brightness), means you need at least a 28A power supply (in total). And don't draw the LED current through the Arduino, or you will fry it's voltage regulator or diode.

I corrected the needed current for the supply XD 28A instead of 2,8A

And you might want to look at this guide from Adafruit. It describes, how you use the WS2812 LEDs and what you have to consider.

I need two pins for stepper Nema 17, and the driver is DRV8825 Stepper Driver ...

The power supply is old pc power supply Model LPG12 550W ATX Computer Power Supply Desktop PC

I don't know, if this computer power supply can give you enough current. Source it's datasheet for the current, that you can get out of the 5V pins. 28A is a lot. Be sure to use cables, that are big enough, or they will melt from the current.

Take care about timing issues such that stepper motor and WS2812 don't interfere.

If that's only 6 on/off (or even fading) LED groups (no RGB-color led stripes) and one stepper motor, any Arduino (Uno / Nano) would do. There are clones, even cheaper than the original.
The peripheral electronics:

Motor driver
Transistors to switch the LED (77 standard LED need 1.5 A, so you have to search for Logic Level MOSFET transistors)

are as expensive as the controller itself,
... and wiring all those LEDs is the hardest work.

The LEDs are WS2812B strips, meaning that you don't need transistors to switch them. The WS2812B is actually the driver chip of each RGB LED in that strip and already consists the needed transistors. You only need to connect the data line to the Arduino

the 6* 77 is because of the design.


text:
GSM incoming bytes from UART not complete
I have used AT commands to read incoming bytes from serial buffer from SIM900A but I cannot get the complete message using the code below:

while(ss.available()>0)
{
 inChar=ss.read();
 inString+=inChar;
}

Serial.println("Received messaged: ");
Serial.println(inString);

inString="";

However this one below works:
if(ss.available()>0)
{
  inString=ss.readString();
}

Serial.println("Received messaged: ");
Serial.println(inString);

inString="";

I wonder what is the difference?

How big is inString? Could you please post a Minimal, Reproducible Example

The data arrive over serial very slow compared to MCU speed. In the first snippet you stop reading at first gap between bytes (available is 0). In the second snippet the function readString will wait for the next byte until a second (at default).