text:
SD writing problem
I have an Arduino code for logging sensor data, time and date. Then I store all the data in the SD card and then I will send the sensor value to another node by using Lora. but I can't write the data in the SD card. Please help me to solve this problem. The code is also attached.
#include <RHReliableDatagram.h>
#include <RH_RF95.h>
#include "RTClib.h"
#include <SPI.h>
#include <SD.h>

RTC_DS1307 rtc;
File myFile;

#define node_address 12
uint8_t gateway_address = 11;
const int sensor_pin = A1;
float level;

/* Chip selection */
const int CS1 = 8;/*SD Card*/
const int CS2 = 10;/*LoRa*/

/* Configure LoRa driver */
RH_RF95 driver(10,2);
RHReliableDatagram manager(driver,node_address);

void setup () {
  pinMode(sensor_pin, INPUT);
  pinMode(CS1,OUTPUT);
  pinMode(CS2,OUTPUT);
//  SPI.begin();`
  /*--------Serial port connection setup--------*/
  Serial.begin(9600);

  /*----------RTC Initialization----------*/
  Serial.println(F("Initializing RTC...!"));
  if (! rtc.begin()) {
    Serial.println(F("Couldn't find RTC"));
  }
  if (! rtc.isrunning()) {
    Serial.println(F("RTC is NOT running!"));
//    rtc.adjust(DateTime(2019, 11, 12, 12, 32, 0)); // (Year,Month,Date,Hour,Min,Sec)
  }

  /*----------SD CARD Initialization----------*/
  digitalWrite(CS2,HIGH);
  delay(500);
  digitalWrite(CS1,LOW);
  Serial.println(F("Initializing SD card..."));
  if (!SD.begin(CS1)) {
    Serial.println(F("initialization of SD Card is failed!"));
    return;
  }
  Serial.println(F("Initialization of SD Card is done."));
  /*----------LoRa Initialization----------*/
  digitalWrite(CS1,HIGH);
  delay(500);
  digitalWrite(CS2,LOW);
  if (manager.init())
  {
    Serial.println(F("LoRa Successfully Initialised "));
  } else {
    Serial.println(F("LoRa initialization failed"));
  }
  driver.setFrequency(433.0);
  driver.setTxPower(14,false);
  Serial.println();
}

void loop () {
  DateTime now = rtc.now();
  /*----------Date----------*/
  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.print(now.day(), DEC);
  Serial.print(',');
  /*----------Time----------*/
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();

  /*----------SD card----------*/
  digitalWrite(CS2,HIGH);
  delay(500);
  digitalWrite(CS1,LOW);
  delay(100);
  myFile = SD.open("test.txt", FILE_WRITE);
  if (myFile) {
    /*----------Saving Date----------*/
    myFile.print(now.year(), DEC);
    myFile.print('/');
    myFile.print(now.month(), DEC);
    myFile.print('/');
    myFile.print(now.day(), DEC);
    myFile.print(',');
    /*----------Saving Time----------*/
    myFile.print(now.hour(), DEC);
    myFile.print(':');
    myFile.print(now.minute(), DEC);
    myFile.print(':');
    myFile.print(now.second(), DEC);
    myFile.println(',');
    level = analogRead(sensor_pin);
    myFile.print(level);
    myFile.println();
    myFile.close();
  } else {
    Serial.println("Error opening test.txt");
  }
  delay(500);
  digitalWrite(CS1,HIGH);
  delay(500);
  digitalWrite(CS2,LOW);
  char data[RH_RF95_MAX_MESSAGE_LEN];
  sprintf(data,"$%d#%d",node_address,level);
  Serial.print("Level transferred is ");
  Serial.println(data);
  Serial.println(sizeof(data));
  if(!manager.sendtoWait((uint8_t*)data,sizeof(data),gateway_address))
  {
    Serial.println("Gateway offline");
  }
  delay(500);
}

let the library handle the CS pin

Note from the SD Library documentation: "Note that even if you don't use the hardware SS pin, it must be left as an output or the SD library won't work."  SS pin for nano is 10 as far as I know. You use the pin then as a chip select for LoRa first, Probable the RoRa lib does something with it, so the SD lib got issues with it. Perhaps you try to exchage the CS pins. I haven't found any problem reported  with changing the SS pin for the LoRa Lib. And: As Juraj said: why do you write to the CS1 and CS2 if the SD and LoRa libraries have control over it?

@PeterPaulKiefer, CS pin is output. this is the most common use of the SS pin in master mode. As CS pin for the first SPI device

The OP uses two CS pins: one for LoRa (10) and one for SD (8). Both are set to output, that's right. But, there is a note in the SD lib doc that, even if one changes the CS/SS pin, one has to set the pin 10 to output. For me this is a hint that pin 10 still influences the SD lib, even if it is not used. I don't know the kind of influence (think of the Lora sets the CS pin 10 to input until it needs it; for what reason ever). So there may be an impact the LoRa lib has to the SD Lib. It's just an idea.

@PeterPaulKiefer The "influence" is in hardware. The direction register for pin 10 defines whether the SPI peripheral operates in Master or Slave mode (INPUT = slave, OUTPUT = master). If you change pin 10 to INPUT then SPI just won't work.

@Majenko Sorry, but I never said I want to change it to INPUT. I said that pin 10 has still impact on the SD lib. As you gave the hint I'm missing, I could still imagine situations where LoRa lib has impact that let the SD lib fail. E.g. the LoRa lib acts as a slave and therefor sets pin 10 to an input. As I don't know if the LoRa lib acts that way. it's just a guess. But it could also be a misplaced cable or something else. user60840: If you add a picture of your setup and provide links to the libs you used we could check that too.

You should not manually control the SD card's CS pin.  By doing so you are confusing both the library and the SD card.
There is a special operation with SD cards in "SPI" mode that isn't part of the SPI standard as part of the initialization routine whereby the master (the Arduino) must send at least 72 clock pulses to the card with the CS pin held HIGH.
By manually setting the CS pin LOW you are breaking that.
There is no call for you to ever do anything for the CS pin other than tell the library what it is - the library does everything else for you. So remove all references to digitalWrite(CS1, ...) from your code.


text:
Help with Stair Lighting using HC-SR04 sensor and WS2812 LED Strip
Excuse my naivete in this as I am very new to Arduino and the programming of. I am trying to put together a project for stair lighting triggered by a ultrasonic sensor at the bottom of the stairs and turned off by an ultrasonic sensor at the top of the stairs and vise versa. I am using an WS2812 LED strip and have the lights travel up the stairs when going up and down when going down. I'm sure this is a project many of you have seen. I have searched the net and youtube and have found many examples of this project, none that I can find using the HC-SR04 sensor. I have managed to cobble together a code which works fine in both direction but it is intermittent in working. I'm sure it is something to do with timings as sometimes it will work fine first time but then others the sensor needs to be blocked for a couple of seconds.
I would also like to add an LDR to the project so it is only active at night. If any of you can point me in the right direction I would be really grateful. I have attached the code so you can see where I am at.
This is just a test code and the final project will have around 200 LEDS.
Thanks

#include <FastLED.h>
#define trigPin_up 2
#define echoPin_up 3
#define trigPin_down 4
#define echoPin_down 5
#define LED_PIN     7
#define NUM_LEDS    13
CRGB leds[NUM_LEDS];

void setup() {

    //Set Serial
  Serial.begin(9600);

  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);

  pinMode(trigPin_up, OUTPUT);
  pinMode(echoPin_up, INPUT);
  pinMode(trigPin_down, OUTPUT);
  pinMode(echoPin_down, INPUT);

}
 void loop(){
 if (trigPin_up, HIGH && trigPin_down, LOW);
 {
   short duration, distance;
  digitalWrite(trigPin_up, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin_up, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin_up, LOW);
  duration = pulseIn(echoPin_up, HIGH);
  distance = (duration/2) / 29.1;

  if (distance <= 50) {
  leds[0] = CRGB(255, 225, 255);
  FastLED.show();
  delay(100);
  leds[1] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[2] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[3] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[4] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[5] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[6] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[7] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[8] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[9] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[10] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[11] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[12] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[13] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  }

{    short duration, distance;
  digitalWrite(trigPin_down, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin_down, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin_down, LOW);
  duration = pulseIn(echoPin_down, HIGH);
  distance = (duration/2) / 29.1;

  if (distance <= 50) {
  leds[0] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[1] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[2] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[3] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[6] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[7] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[8] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[9] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[10] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[11] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[12] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[13] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  }

else
if (trigPin_up, LOW && trigPin_down, HIGH);
  {

     short duration, distance;
  digitalWrite(trigPin_down, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin_down, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin_down, LOW);
  duration = pulseIn(echoPin_down, HIGH);
  distance = (duration/2) / 29.1;

  if (distance <= 50) {
  leds[13] = CRGB(255, 225, 255);
  FastLED.show();
  delay(100);
  leds[12] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[11] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[10] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[9] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[8] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  leds[7] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[6] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[5] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[4] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[3] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[2] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[1] = CRGB(255, 255, 255);
  FastLED.show();
   delay(100);
   leds[0] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);
  }
{
  short duration, distance;
  digitalWrite(trigPin_up, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin_up, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin_up, LOW);
  duration = pulseIn(echoPin_up, HIGH);
  distance = (duration/2) / 29.1;

    if (distance <= 50) {
  leds[13] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[12] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[11] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[10] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[9] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[8] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  leds[7] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[6] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[5] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[4] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[3] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[2] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[1] = CRGB(0, 0, 0);
  FastLED.show();
   delay(100);
   leds[0] = CRGB(0, 0, 0);
  FastLED.show();
  delay(100);
  }
}

  }
}
 }
 }

There are a couple things with your code which you might need to look into.
Note: I'm doing this ontop of my head, so please correct me if I say something incorrect. ]
First, to check if values are equal, with an if-statement you'd have to use:
//if (trigPin_up, HIGH && trigPin_down, LOW); not like this.
if (trigPin_up== HIGH && trigPin_down== LOW) {.....} //But like this

Do not use the ';' because that would be then end of the statement.
Second, there seems to be a random '{' without any statement beforehand, at line 88.
Extra tip
You can use for loops!
So:
leds[0] = CRGB(255, 225, 255);
  FastLED.show();
  delay(100);
  ....
  leds[13] = CRGB(255, 255, 255);
  FastLED.show();
  delay(100);

becomes:
for (int i = 0; i <14; i++){
    leds[i] = CRGB(255, 225, 255);
  FastLED.show();
  delay(100);
  }

As a good exercise, could you try to clean up your code, edit it in the OP, and try if it works then?

The for loop at the end should only go up to 12 instead of 13, since there are only 13 elements in the array

I don't think so. At the top there are 13 elements defined, but there should be 14, since he wants to do 0 until 13, which are 14 different numbers.

But then the array needs to be define with 14 elements. NUM_LEDS is currently 13. If you are assuming, that the OP has 14 LEDs, you should include that assumption and also say, that the definition would have to be changed for that. People tend to copy&paste from the internet a lot, so it would be better to explain this, instead of just quietly assuming it.

Calvin Bootsman is right with the errors, that he described, but there are more problems in your code.

Look at these two lines, that I got from your sketch. I already corrected, what Calvin had to say about the if statement.
#define trigPin_up 2
if (trigPin_up == HIGH && trigPin_down == LOW){

You define trigPin_up as the number two. A define is read by the preprocessor. It will replace all occurances of trigPin_up with the number 2. HIGH and LOW are also defines (defined in the Arduino core) with the values 1 and 0. They also get replaced. After that the code goes to the actual compiler. So the compiler sees this if statement:
if( 2 == 1 && 4 == 0)

2 isn't equal 1 and 4 isn't equal 0, so the result is always false. That corrupts your complete logic. I'm sure you want to read the state of the pin. trigPin_up and siblings are only the pin numbers. For getting the real electrical state of the pin you need to actually read it via digitalRead():
if(digitalRead(trigPin_up) == HIGH && digitalRead(trigPin_down) == LOW){

You can simplify this even more, when you know, that zero is treated as false and every other value as true:
if(digitalRead(trigPin_up) && !digitalRead(trigPin_down)){

The ! before the second digitalRead() does a negation, so that the part after the && will become true, if digitalRead(trigPin_down) evaluates to false.
Now look at these lines:
#define NUM_LEDS    13
CRGB leds[NUM_LEDS];
leds[13] = CRGB(0, 0, 0);

You create an array named leds with NUM_LEDS (13) elements. The first index is 0 (as we start to count from zero in most programming languages). But that means, that the last index in the array is 12, not 13. When doing leds[13]=... you actually write to a memory address outside of your array. It could be everything, what is saved there. And you overwrite it. This often is a hard to diagnose problem, since it can have very weird consequences. Calvin Bootsman also did this wrong in his answer. For the for loop you only should count to 12, meaning using i < 13 or i < NUM_LEDS in the for loop.
Then I guess you don't really understand how the logic of interfacing the HC-SR04 works. The trigger pins, that you define, are outputs. Their state will only change, if you yourself change it via digitalWrite(). But that cannot happen, as you enclosed the statements doing it into the if statement. It does not make sense to read these pins either. Instead you should write if statements with the calculated distance. You could go with the following flow in you loop() function: Trigger first HC-SR04, read the echo back, trigger second HC-SR04, read the echo back, if statement to compare the calculated distances to a trigger value, in there if statements to decide, which one was triggered, execute the corresponding code in it.

Honestly I'm suprised, that your code even compiled. You should look into some basic C/C++ tutorials, so that you get the programming syntax right. Also you should carefully think about the logic of your program. Often it is better to first write down short notes, what the logic of the program should be, without really writing the code. That helps with focussing on the logic instead of the syntax. That can be done afterwards.

chrisl thanks for the feedback I will have a look into some basic C/C++ tutorials.

source: Stack Exchange

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

sort: votes


text:
I can't receive string that I have sent through nrf correctly
I'm using arduino uno and nrf24l01. to monitor sensor data.
But this is the message that master receives:

⸮

this is my slave code.
void monitoring() {
    delay(10);
    radio.stopListening();
    int soilMoisture = analogRead(A5);
    int light = analogRead(A4);
    float temp = analogRead(A3);
    temp = temp * 0.48828125;
    int ltemp = int(temp);
    String message = String(soilMoisture) + "," + String(light) + "," +    String(ltemp);
    Serial.println(message);
    delay(200);
    radio.write(&message, sizeof(message));
    delay(50);
    radio.startListening();
    delay(10);
}

and here is my master code.
while (1) {
    if (radio.available()) {
      char message[32] = "";
      radio.read(&message, sizeof(message));
      delay(500);
      Serial.println(message);
}

Remove the & in the master code line, change
 radio.read(message, sizeof(message));

to
radio.read(message, sizeof(message));

message is an array, so either you should pass the address of the first character (&message[0]), or simply pass message.
Another problem is sending a String in the slave code (using type String). It's better not to use this type anyway, but you probably have to convert it to a character array of the same type as in the master code.
You can use the function StringToCharArray for that, see StringToCharArray.

Thank you very much

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


text:
cant figure out how to fix this compile error
evrything worked for a bit and changed to much to get it working again. dont really understand the error.
[![C:\Users\bavob\AppData\Local\Temp\ccyfrkaL.ltrans0.ltrans.o: In function `loop':
C:\Users\bavob\Documents\Arduino\counte_up/counte_up.ino:96: undefined reference to `num_Write(int)'
collect2.exe: error: ld returned 1 exit status
exit status 1
Fout bij het compileren voor board Arduino/Genuino Uno]1]1
  { 1, 1, 1, 1, 1, 0, 1 }, // 0
  { 0, 1, 1, 0, 0, 0, 0 }, // 1
  { 1, 1, 0, 1, 1, 1, 0 }, // 2
  { 1, 1, 1, 1, 0, 1, 0 }, // 3
  { 0, 1, 1, 0, 0, 1, 1 }, // 4
  { 1, 0, 1, 1, 0, 1, 1 }, // 5
  { 1, 0, 1, 1, 1, 1, 1 }, // 6
  { 1, 1, 1, 0, 0, 0, 0 }, // 7
  { 1, 1, 1, 1, 1, 1, 1 }, // 8
  { 1, 1, 1, 0, 0, 1, 1 }  // 9
};

int pin = 2;
int buttonState = 0;
const int button = 12;
int led = 13;
int randVal;
bool pressVal;
void num_Write(int);
void setup() {
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  pinMode(button, INPUT);
}

void loop() {
  buttonState = digitalRead(button);
  if (buttonState == LOW) {
    turnOff();
    pressVal = false;
  }
  else
  {
    if (pressVal == false)
    {
      randVal = rand() % 10;
      pressVal = true;
    }
    Serial.println(randVal);
    if (randVal == 0)
    {
      void zero(int number);
      num_Write(0);
    }
    else if (randVal == 1)
    {
      void one(int number);
      num_Write(1);
    }
    else if (randVal == 2)
    {
      void two(int number);
      num_Write(2);
    }
    else if (randVal == 3)
    {
      void three(int number);
      num_Write(3);
    }
    else if (randVal == 4)
    {
      void four(int number);
      num_Write(4);
    }
    else if (randVal == 5)
    {
      void five(int number);
      num_Write(5);
    }
    else if (randVal == 6)
    {
      void six(int number);
      num_Write(6);
    }
    else if (randVal == 7)
    {
      void seven(int number);
      num_Write(7);
    }
    else if (randVal == 8)
    {
      void eight(int number);
      num_Write(8);
    }
    else
    {
      void nine(int number);
      num_Write(9);
    }
  }
}

void zero(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}

void one(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}

void two(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void three(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void four(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void five(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void six(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void seven(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void eight(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void nine(int number)
{
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}
void turnOff()
{

}

You call function num_Write a lot, you create a forward declaration:
void num_Write(int);
But you forgot to create the implementation.
If you would have forgot the forward declaration the function would not be known at all (and you would get a compiler error). But with the forward declaration you let the compiler know the signature of num_write (so the return value and argument types).
When the linker wants to link all object (.o) files together it cannot find an implementation of the function num_write and you get this error. Hence ld is the linker.

So what should I need to do to fix it?

create an implementation for num_Write … so write void num_Write(int value) { … } where … contains the implementation (what the function should do).


text:
NRF24l01 receiving only zeros
I want to transmit and receive data with the help of NRF24l01 modules. I tried to deliver joystick values from UNO to UNO but I have trouble about it.
In receiver side I have only zeros. I have been connect pins according to pin out orders.
ce--9
csn----10
sck----13
mosi----11
miso-----12

on both side. I am using module adapter to provide constant current and feeding with 3.3 volt and 5 volt another one. Both did not work. I bought new modules and adapters and connected 3.3 volt but nothing changed. I could not understand the problem help me please. Here is are my sketches:
RECEIVER

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#define CE_PIN   9
#define CSN_PIN 10
const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(CE_PIN, CSN_PIN);
int data[3];
void setup()
{
  Serial.begin(9600);
  SPI.begin();
  radio.begin();
  radio.openReadingPipe(1, pipe);
  radio.startListening();
  radio.setPALevel(RF24_PA_MAX);
}

void loop() {
  if ( radio.available() ) //Eğer sinyal algılarsan...
  {

    radio.read( &data, sizeof(data) );

    Serial.print("data[0]=");
    Serial.println(data[0]);
    Serial.print("data[1]=");
    Serial.println(data[1]);
    delay(300);
    radio.stopListening();

  }
  else {
    Serial.println("no signal");
  }
}

TRANSMITTER
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#define PIN_ANALOG_X 0
#define PIN_ANALOG_Y 1
#define CE_PIN   9
#define CSN_PIN 10
const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(CE_PIN, CSN_PIN);
int data[2];

void setup() {

  // Start serial because we will observe values at serial monitor
SPI.begin();
  Serial.begin(9600);
  radio.begin();
  radio.openWritingPipe(pipe);
  radio.setPALevel(RF24_PA_MAX);
}

void loop() {

  // Print x axis values

  Serial.print("x: ");

  Serial.println(analogRead(PIN_ANALOG_X));

  // Print y axis values

  Serial.print("y: ");

  Serial.println(analogRead(PIN_ANALOG_Y));
  data [0] =map( analogRead(PIN_ANALOG_X),0,676,0,255);
  data [1] = map(analogRead(PIN_ANALOG_Y),0,676,0,255);

 radio.write( &data, sizeof(data) );
  Serial.println("data0");
  Serial.println(analogRead(PIN_ANALOG_X));
  Serial.println("data1");
  Serial.println(analogRead(PIN_ANALOG_Y));

Serial.println(data [0]);
Serial.println(data [1]);
  // Some delay to clearly observe your values on serial monitor.

  delay(300);

}

Why do you want to receive 3 ints at the receiver but you send 2 ints at the transmitter? Also why  radio.stopListening(); after one packet is received?

Actually ı found some codes from internet and re-arrange them. At the begining codes that ı found were not containing  radio.stopListening(); command and also it was not working. I wrote it because of ı thought it could be problem but it did not work despite of it.
int data[2]; is a mistake and ı re-arranged it as int data[3];

But at the transmitter side you send a int data[2] array, so it also has to be the same at the receiver. I would also remove the Serial.println("no signal"); in the receiver as to not spam the console. Do you then see any output in the receiver?

I delete the Serial.println("no signal"); and wrote int data [2] at both side but nothing has changed , at receiver side ı have still zeros

"Have zeroes" meaning it prints "data[0]=0 data[1]=0"?

yes at receiver's seril port screen ı have that;
data[0]=0;
data[1]=0;

So th data reception works, because radio.available() returned true and read the data. Are the source data at the transmitter also 0? How did you connect the transmitter to the joystick?

ı am using joystick shield v1.a. I am trying to transmit joystick values hence source data are not zero.There is a place to nrf24l01 and ı directly connected to this place but ı have also tried to connect into pins of shield with same configuration of receiver but nothing has been changed.

Again, what does the transmitter print when it sends data?

transmitter print joystick values as data[0]=329; and data[1]=335; but receiver prints data[0]=0; data[1]=0;


text:
Arduino UNO: Autonomous Firetruck Coding (Fire Detection) and Connection (Water Pump) Problem
I am currently working on an autonomous firetruck project. Its already doing obstacle avoidance however, I still don't know the proper code for fire detection. It already detects fire but what I want to happen is the motor will stop for a second when it detects fire then it will go forward directly to the fire and put it off using a water pump. I already made a code but it is not working. Secondly, where I will insert the GND and VCC of the water pump? I don't know its connection.
Materials:
Arduino UNO
Ultrasonic Sensor
Flame Sensor
Servo Motor
Button
Mini Breadboard
L298n
2wd Robot Kit
Here is the code:
#include <Servo.h>
#include "Ultrasonic.h"

const int button = 2;
const int led    = 3;
const int pump = 4;
const int motorA1= 6;
const int motorA2= 9;
const int motorB1=10;
const int motorB2=11;
const int flame=12;
const int buzzer=13;

Ultrasonic ultrasonic(A4 ,A5);
Servo myservo;

int distance;
int checkRight;
int checkLeft;
int function=0;
int buttonState=0;
int pos=90;
int flag=0;
int flame_detected=0;

void setup(){
 Serial.begin(9600);
 myservo.attach(5);
 myservo.write(pos);
 pinMode(button, INPUT_PULLUP);
 pinMode(led,  OUTPUT);
 pinMode(buzzer, OUTPUT);
 pinMode(motorA1,OUTPUT);
 pinMode(motorA2,OUTPUT);
 pinMode(motorB1,OUTPUT);
 pinMode(motorB2,OUTPUT);
 pinMode(flame,INPUT);
 pinMode(pump,OUTPUT);
}

void loop(){
 flame_detected = digitalRead(flame);
  if (flame_detected == 1)
  {
    Serial.println("No flame detected. stay cool");

    //Check button state
    buttonState = digitalRead(button);
    unsigned long currentMillis = millis();

    if (buttonState == LOW) {
      delay(500);
      if ( flag == 0){
       function = 1;
       flag=1;
      }
      else if ( flag == 1){
       function = 0;
       flag=0;
     }
   }

   if (function == 0){
    myservo.write(90);
    stop();
    digitalWrite(led, HIGH);
    }
   else if (function == 1){
    //Read distance...
    distance = ultrasonic.Ranging(CM);

   if (distance > 20){
    forward();

    digitalWrite(led,LOW);
   }
    else if (distance <=20){
    stop();

    digitalWrite(led,HIGH);

    for(pos = 0; pos < 180; pos += 1){
     myservo.write(pos);
     delay(10);
     //myservo.write(90);
    }

    checkLeft = ultrasonic.Ranging(CM);
    //myservo.write(90);

    for(pos = 180; pos>=0; pos-=1){
    myservo.write(pos);
    delay(10);
    //myservo.write(90);
    }

    checkRight= ultrasonic.Ranging(CM);

          myservo.write(90);

           if (checkLeft < checkRight){
             left();
             delay(400);
             }
           else if (checkLeft > checkRight){
             right();
             delay(400);
           }
           else if (checkLeft <=10 && checkRight <=10){
             backward();
             left();
           }
   }
 }

}

else if (flame_detected == 0) {
  Serial.println("Flame detected...! take action immediately.");
  buzzerwarning ();

  stop();

  if(distance > 25){
  forward();
  }
  else if (distance <= 25){
  stop();
  digitalWrite (pump, HIGH);
  }

  digitalWrite (pump,LOW);
  flame_detected == 1;
  }
}
void backward(){
 digitalWrite(motorA1, HIGH);
 digitalWrite(motorA2, LOW);
 digitalWrite(motorB1, HIGH);
 digitalWrite(motorB2, LOW);
}

void forward(){
 digitalWrite(motorA1, LOW);
 digitalWrite(motorA2, HIGH);
 digitalWrite(motorB1, LOW);
 digitalWrite(motorB2, HIGH);
}

void left(){
 digitalWrite(motorA1, HIGH);
 digitalWrite(motorA2, LOW);
 digitalWrite(motorB1, LOW);
 digitalWrite(motorB2, HIGH);
}

void right(){
 digitalWrite(motorA1, LOW);
 digitalWrite(motorA2, HIGH);
 digitalWrite(motorB1, HIGH);
 digitalWrite(motorB2, LOW);
}

void stop(){
 digitalWrite(motorA1, LOW);
 digitalWrite(motorA2, LOW);
 digitalWrite(motorB1, LOW);
 digitalWrite(motorB2, LOW);
}

void buzzerwarning () {
int i=0;

  do {
    i++;
    tone(buzzer, 7500);
    delay (700);
    tone(buzzer, 5500);
    delay (700);
    noTone (buzzer);
    delay (0);

  }
  while(i<2);

delay(0);
}

Thanks.

There are 2 questions here.  It would be best to separate the two questions in two independent posts.  Also, simplify your program so it only contains the code which does not work as expected.  Some times there is a good reason to post all your code.  But in this case all you are asking about is moving toward a heat source.

where I will insert the GND and VCC of the water pump? .... the pump is just a motor ... you control it the same way as the motors for the wheels

How is your code not working? What doesn't behave as expected? You always have to provide a full problem description

What do you use the L298N for? If it's for the pump, a simple transistor would do the job as well

Usually, code using delay()s is poor. You should implement a (non-blocking) state machine. This will probably solve one of your problems

I use a relay for the pump and it is now working the only problem is the code
This is the part of the code that is not working:
if(distance > 25){
forward();
}
else if (distance <= 25){
stop();
digitalWrite (pump, HIGH);
}
digitalWrite (pump,LOW);
flame_detected == 1;
}


text:
can't interface SIM900 GSM Module with Arduino Mega
I am trying to interface SIM900 GSM Module with Arduino Mega. When I send AT command on COM port in carriage mode then its not sending 'ok' back so I think the interface is not successful. Here is the resource which I referred to - Link.
Have a look below:-
Code:-
#include <SoftwareSerial.h>     //please put less than and greater than sign respectively in place of  =

SoftwareSerial SIM900(10, 11); // (RX, TX). please zoom image above to see exactly what is going where.

void setup()
{
  SIM900.begin(19200);               // the SIM900 baud rate
  Serial.begin(19200);

}

void loop()
{

  if (SIM900.available())              // if date is comming from softwareserial port ==> data is comming from gprs shield
  Serial.write(SIM900.read());
  if (Serial.available())                // if data is available on hardwareserial port ==> data is comming from PC or notebook
  SIM900.write(Serial.read());

}

Electric Connection:-

How to interface it correctly?
Update:- I added a 5v 2A power supply and changed Arduino Rx/Tx pin to 10/11. Added micro sim at the back but still the same result

You can not power it over the Arduino. The module need up to 2A. The Arduino will never be able to give you all this power. Probably also your USB is not able to do it if connected to a PC.

I suspected so. Thanks, will try it. I thought without sim it will draw less power.

I added a 5v 2A power supply and changed arduino Rx/Tx pin to 10/11. Added micro sim at the back but still the same result

Are the jumpers on the right position? Are you using CR as end line? Is 19200 the right baud rate? Is GND connected correctly? Check this tutorial: https://randomnerdtutorials.com/sim900-gsm-gprs-shield-arduino/

did all other, what is CR as end line?

Carriage Return. Some times only LF (Line Feed) is sent.


text:
It gives some glitching on 7 segment display
It gives the right value on the monitor but it doesnt display the value on my display.
int pinNumb[7] = {2, 3, 4, 5, 6, 7, 8};
int num_array[11][7] = {
  { 1, 1, 1, 1, 1, 0, 1 }, // 0
  { 0, 1, 1, 0, 0, 0, 0 }, // 1
  { 1, 1, 0, 1, 1, 1, 0 }, // 2
  { 1, 1, 1, 1, 0, 1, 0 }, // 3
  { 0, 1, 1, 0, 0, 1, 1 }, // 4
  { 1, 0, 1, 1, 0, 1, 1 }, // 5
  { 1, 0, 1, 1, 1, 1, 1 }, // 6
  { 1, 1, 1, 0, 0, 0, 0 }, // 7
  { 1, 1, 1, 1, 1, 1, 1 }, // 8
  { 1, 1, 1, 0, 0, 1, 1 }, // 9
  { 0, 0, 0, 0, 0, 0, 0 }  //nothing
};

int pin = 2;
int button = 12;
int buttonVal;
int randVal;
bool pressVal;
void setup() {
  Serial.begin(9600);

  for (int i = 0; i < 7 ; i++)
  {
    pinMode(pinNumb[i], OUTPUT);
  }
  pressVal = false;
  pinMode(button, INPUT);
}

void loop() {
  buttonVal = digitalRead(button);
  if (buttonVal == 0)
  {
    //zero();
    turnOff();
    pressVal = false;
  }
  else
  {
    //zero();
    if (pressVal == false)
    {
      randVal = rand() % 10;
      pressVal = true;
      delay(100);
    }
    Serial.println(randVal);
    if (randVal == 0)
    {
      zero();

    }
    else if (randVal == 1)
    {
      one();

    }
    else if (randVal == 2)
    {
      two();

    }
    else if (randVal == 3)
    {
      three();

    }
    else if (randVal == 4)
    {
      four();

    }
    else if (randVal == 5)
    {
      five();

    }
    else if (randVal == 6)
    {
      six();

    }
    else if (randVal == 7)
    {
      seven();

    }
    else if (randVal == 8)
    {
      eight();

    }
    else
    {
      nine();

    }
  }
}

void zero()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[0][j]);
    pin++;
  }
}

void one()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[1][j]);
    pin++;
  }
}

void two()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[2][j]);
    pin++;
  }
}
void three()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[3][j]);
    pin++;
  }
}
void four()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[4][j]);
    pin++;
  }
}
void five()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[5][j]);
    pin++;
  }
}
void six()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[6][j]);
    pin++;
  }
}
void seven()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[7][j]);
    pin++;
  }
}
void eight()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[8][j]);
    pin++;
  }
}
void nine()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[9][j]);
    pin++;
  }
}
void turnOff()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }

}

a 7 segment display, a randopm value generated, pin 2-9 connected from arduino uno to the 7 segment display, The 7 segment display doesnt show the generated number just some random digits.

your code is overly repetitious ... you could remove 95% of the code and still retain desired functionality ... you also have some useless code ... for instance, inside the void zero() function, what is the point of having the first for loop? ... same for all the other functions

I am a complete noob to this so i just used what I learned, if you could give a bit more of a concrete explenation of what you mean that would be helpfull.

take a close look at the void zero() function ... what is the code doing? ... remember that the whole function executes in a few milliseconds .... do you really need the first for loop?

So do i just remove it, because that function made it so the display had no other digits on.

you only have one digit ... you have 7 segments

ah i mean segments;

You are continually incrementing the pin variable via pin++, but you are never resetting it to the start (2?) when a new number is to be written.  So it might work the first time but never after that.
Also, you clear the display with digitalWrite(pinNumb[i],LOW);
But you turn segments on with digitalWRite(pin,....); pin++.
Shouldn't you turn the segments on with digitalWrite(pinNumb[i] . . ?

yeah that would be easier but for the exercise i need to use an array, so that isnt possible.

my point is that you are NOT using the array when turning on the segments.

These can all be byte instead of int to save on memory:
int pinNumb[7] = {2, 3, 4, 5, 6, 7, 8};
int num_array[11][7] = {
  { 1, 1, 1, 1, 1, 0, 1 }, // 0
  { 0, 1, 1, 0, 0, 0, 0 }, // 1
  { 1, 1, 0, 1, 1, 1, 0 }, // 2
  { 1, 1, 1, 1, 0, 1, 0 }, // 3
  { 0, 1, 1, 0, 0, 1, 1 }, // 4
  { 1, 0, 1, 1, 0, 1, 1 }, // 5
  { 1, 0, 1, 1, 1, 1, 1 }, // 6
  { 1, 1, 1, 0, 0, 0, 0 }, // 7
  { 1, 1, 1, 1, 1, 1, 1 }, // 8
  { 1, 1, 1, 0, 0, 1, 1 }, // 9
  { 0, 0, 0, 0, 0, 0, 0 }  //nothing
};

int pin = 2;
int button = 12;
int buttonVal;
int randVal;

In addition, the array can be reduced to 11 bytes:
0bFD, // 0
0bC0, // 1
0bDE, // 2
etc.

Then your functions can do direct port manipulation to send bits 0-5 to the Port for D2 to D7, and bit to D8.
As written, these functions probably need some hold time so they don't just flash the LED and disappear:
void one()
{
  for(int i = 0; i < 7 ; i++)
  {
    digitalWrite(pinNumb[i],LOW);
  }
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin, num_array[1][j]);
    pin++;
  }
}

what command should i use to hold them delay isntr really doing anything.

Longer delay()?  Like 250 (quarter second)? Experiment, see what looks good to you.

Now only the firts generated number gets shown properly all others after that are just broken segments.


text:
Will this code for braking of dc motor using sensor work?

#define trigPin 13
#define echoPin 14
#define e1 10  // Enable Pin for motor 1
#define t1 8   // Control pin 1 for motor 1
#define t2 9   // Control pin 2 for motor 1
#define led 3
#define led2 5
#define buzzer 4

float duration,distance;
#include<SoftwareSerial.h>

void setup() {
 Serial.begin(9600);
 pinMode(trigPin,OUTPUT);
 pinMode(echoPin,INPUT);
 pinMode(e1, OUTPUT);
 pinMode(t1, OUTPUT);
 pinMode(t2, OUTPUT);

}

void loop() {
  digitalWrite(e1, HIGH);
  digitalWrite(t1, HIGH);
  digitalWrite(t2, LOW);

  digitalWrite(trigPin,LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin,HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin,LOW);

duration=pulseIn(echoPin,HIGH);
distance=(duration/2)*0.0343;
Serial.print("Distance= ");
if(distance>=400||distance<=2)
{
  Serial.println("out of range");
}
else if(distance<=100&&distance<=50)

{
  digitalWrite(led,HIGH);
  delay(1000);
  analogWrite(e1,157);
  digitalWrite(t1,HIGH);
  digitalWrite(t2,LOW);
  delay(500);
}
else if(distance<=50&&distance>=25)
{
  digitalWrite(buzzer,HIGH);
  delay(100);
  analogWrite(e1,56);
  digitalWrite(t1,HIGH);
  digitalWrite(t2,LOW);
}
else if(distance<=25&&distance>=10)
{
  digitalWrite(led2,HIGH);
  delay(100);
  analogWrite(e1,0);

}
else if(distance<=390&&distance>=100)
{  digitalWrite(e1, HIGH);
  digitalWrite(t1, HIGH);
  digitalWrite(t2, LOW);

}

delay(500);
}

Have you tested the code? How does it behave different, than you expect? And you should really add a complete description, what the desired behavior is. Just the title is not enough. Please put some effort into writing your question with all the information needed

you do not use a sensor to brake a motor ... you use a motor driver that is controlled by the program ... the sensor is used only for input ... decisions about motor braking can be made as a result of the input .... since you said nothing about what parameter affects braking, your question is not answerable

Please take the [tour], learn how to [ask], and then [edit] your question with additional informations. You will get much better answers then. ;-)


text:
Time counting using millis
I am trying to write a code where photoresistors (a or b) sense blinking of the light, and lights LED (k and d) simultaneosly with that blinking. And I want that when both photoresistors sense dark for more than 3 secs, the LEDs would light up and stay until one of them again gets lighting. But I cannot understand in which part should I put millis time count?

int k = 2;
int d = 3;
int fk = A0;
int fd = A1;
int a = 0;
int b = 0;

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

void loop()
{
  a = analogRead (fk);
  b = analogRead (fd);
  while (a < 1000 && b < 1000)
  {
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    a = analogRead (fk);
    b = analogRead (fd);
  }
  if (a > 1000)
    digitalWrite(2, HIGH);
  else
    digitalWrite(2, LOW);
  if (b > 1000)
    digitalWrite(3, HIGH);
  else
    digitalWrite(3, LOW);
}

Did you say photo resistors & blinking lights??  Keep in mind that photo resistors have an odd valance band.  Specifically, photo resistors will conduct current when lights go on and will continue to conduct current after lights go off for perhaps a second or more.  So if you lights are blinking fast enough, you will never detect the lights going off with photo resistors.

Bilnks are in 1sec interval, I have already tested that, everything works, I'm just stuck with that timing.

What type of light are you blinking to activate the photoresistors?

This is one of those cases where the solution is simply to implement a
finite state machine. Consider a state machine with these three
states:

LIGH: light has been detected by at least one of the sensors, the
LEDs follow the light sensors
SHORT_DARK: neither sensor sees light, both LEDs are off
LONG_DARK: it has been at least three seconds since neither sensor
saw light, both LEDs are on.

The transitions between those states can be depicted by the following
state diagram:

where “darkness detected” means that no sensor sees light, and “light
detected” means that at least one sensor sees light.
As a general rule, it is a good practice to always draw a state diagram
before you start writing code. Once you are sure your diagram describes
the desired behavior, it is almost trivial to translate it into code.
Here is how I would code it:
void loop()
{
    bool light_k = analogRead(IN_K) >= 1000;
    bool light_d = analogRead(IN_D) >= 1000;

    static enum { LIGHT, SHORT_DARK, LONG_DARK } state;
    static uint32_t darkness_start;
    switch (state) {
    case LIGHT:
        digitalWrite(OUT_K, light_k ? HIGH : LOW);
        digitalWrite(OUT_D, light_d ? HIGH : LOW);
        if (!light_k && !light_d) {
            darkness_start = millis();
            state = SHORT_DARK;
        }
        break;
    case SHORT_DARK:
        if (light_k || light_d) {
            state = LIGHT;
        } else if (millis() - darkness_start >= 3000) {
            digitalWrite(OUT_K, HIGH);
            digitalWrite(OUT_D, HIGH);
            state = LONG_DARK;
        }
        break;
    case LONG_DARK:
        if (light_k || light_d) {
            state = LIGHT;
        }
        break;
    }
}

Millis gives you a measure of time.  You can store that measure and compare to it later.  I don't know what in your code represents a sense of dark/light in your code (resistors can be used to raise or lower the measured input depending on your circuit) so you will have to work the following in by replacing stuff in <>
unsigned long lastlight;
void loop()
{
    if (<isLitSensorA>) lastlight = millis();
    if (<isLitSensorB>) lastlight = millis();
    if(millis() - lastlight > 3000){ //3 sec since lastlight
        <LightsAlwaysOn>
    }
    else{
        <BlinkWithLights>
    }
}

Here is a more elegant way to do this. This program doesn't require you to actually count it has been dark, instead it just remembers the time it has last seen the light (how poetic ;). I also added some commentary alongside the code.
// All the variables
int k = 2;        // LED 1
int d = 3;        // LED 2
int fk = A0;      // photoresistor 1
int fd = A1;      // photoresistor 2
int lastLight = 0;

// Set up the LEDs
void setup() {
  pinMode(k, OUTPUT);
  pinMode(d, OUTPUT);
}

void loop()
{
  // Check the photoresitors
  int a = analogRead (fk);
  int b = analogRead (fd);
  if (a > 1000 || b > 1000)
  {
    // Turn LEDs on if one photoresitor senses light
    digitalWrite(k, HIGH);
    digitalWrite(d, HIGH);
    // Also set the last time it was bright to the current time
    lastLight = millis();
  }
  else if (abs(millis() - lastLight) > 3000)
  {
    // Turn LEDs on if it has been dark for more than 3 seconds (that is 3000 milliseconds)
    digitalWrite(k, HIGH);
    digitalWrite(d, HIGH);
  }
  else
  {
    // Turn LEDs off
    digitalWrite(k, LOW);
    digitalWrite(d, LOW);
  }
}

Re “if (lastLight < millis() - 3000)”: here you have a millis-rollover bug. It can be somehow mitigated by if (millis() - lastLight > 3000), but it will still fail if it stays dark for longer than the rollover period. Adding lastLight = millis() - 9000 within the if, or some kind of state variable, can fix that.

Good point, I updated the answer to match that. However, using if (millis() - lastLight > 3000) will not change that. You can bypass the problem by using the absolute value of the difference (this way the LEDs stay dark even if a rollover occurs). I don't understand your suggestion though for the case that it stays dark for longer than 49.5 days.

abs() won't help, but you have to make lastLight an unsigned long. See millis() overflow ... a bad thing? and How can I handle the millis() rollover?. If it stays dark for longer than 49.7 days, millis() will get very close to lastLight, and this code will turn the LEDs off. That won't happen if you repeatedly change lastLight to stay a few seconds behind millis().


text:
ATmega328P - Problem using timer 2 for tone generation
I'm simply trying to use timer 2 for tone generation and what I get is a very faint and strange tone (almost like its modulated somehow as there is a "pulsing" to it). Here's my simple code:
#include <Arduino.h>

#define SPEAKER_PORT PORTC
#define SPEAKER_BIT 2

void setup()
{
  pinMode(A2, OUTPUT);

  TCCR2A = _BV(WGM21);  // CTC mode
  TCCR2B = _BV(CS20);   // clk/1

  OCR2A = 200;  // 8-bit timer, so keep less than 256
  bitSet(TIMSK2, OCIE2A);  // enable OCR2A interrupt
}

void loop()
{
  // NOP
}

ISR(TIMER2_COMPA_vect)
{
  SPEAKER_PORT ^= _BV(SPEAKER_BIT);
}

Any obvious mistakes? Thanks for your help!

I tried the code on an Uno and as you say, it does sound odd.
By my calculations, the frequency is 40kHz (16MHz/(200 x 2)), which is above the threshold of hearing. The sound we are actually hearing is probably the 3rd or 5th harmonic, at a reduced intensity and perhaps subject to jitter.
I tried changing
TCCR2B = _BV(CS20);   // clk/1
to
TCCR2B = _BV(CS21);   // clk/8
which should mean that the frequency is now 5kHz (16MHz/8/(200 x 2)).
It sounds cleaner.

Just posted an answer with a similar conclusion, as I had cross-posted to AVRFreaks.net and got similar advice. Thanks for the help! Glad to validate that this was reproducible for you. I'll mark yours as the solution.

Looks like my tone frequency was possibly just too high for the buzzer I was using, causing strange output.
Adjusting the clock divider fixed the issue. That is, I changed the following:
TCCR2B = _BV(CS20);   // clk/1

to
TCCR2B = _BV(CS22) | _BV(CS20);  // clk/128

and now I get reasonable-sounding tones.
Note that the clock divider you choose is ultimately driven by what frequency range you want to support, and the bit width of the timer. The formula is something like:
freq = 16000000 / d / n / 2

where d is the clock divider value (like 128), and n is the counter value at which to interrupt (what goes in OCR2A for instance). n must fit into the bit width of the specific timer (on ATmega328P timer 1 is 16-bits wide, and timer 2 is 8-bits wide).
Hope this is helpful for anyone else running into these issues. Thanks so much to Kartman over at AVRFreaks.net for pointing me in the right direction.

If you drive the speaker pin from an interrupt, you will inevitably have
some jitter, as the interrupt request will sometimes fire while the CPU
is processing another ISR. This can lead to one of the levels being held
for longer than expected, which in turn leads to spurious frequencies in
the output. Note that these are not really harmonics (harmonics always
have frequencies higher than the fundamental), but rather beating
between different interrupt sources. That's why you are able to hear
something even though the fundamental is well above the hearing range.
If you want to have a clean PWM signal, you should instead generate it
in hardware. Timer 2 for example can drive pins 11 (OC2A) and 3 (OC2B).
See the bits COM2{A1,A0,B1,B0} in TCCR2A.


text:
Can I use laptop USB port to power Nodemcu if every port used
I wonder if a laptop USB port is enough or I have to use an external power supply if the NodeMCU under heavy load. Here is my list of sensors and port used.
3.3V
3.3V
D1 to D7
A0
GND

Sensors: Turbidity sensor, Flow sensor, Temperature sensor, 4 led

That depends on how much current all that needs. We cannot know that. You didn't give us enough information. USB is limited to 500mA

standard current you can draw from a usb port is 500 mili ampere with 5 volt(you may get even more but it is not recommended) . so if you want to calculate
sensors are very low current about 1~2 mA(but you must check out datasheet)
turbidity for example draws 30 mA
temperature ds1820 is 1 mA
flow is up 2 mA
the LEDs based on resistors series with them you normally up to 3 mA for
each(1k series to 3.3 volt)
if you sum up all of them
30+1+2+4*3=45mA
but you should consider other consumers for example if you need 3.3 V you need a regulator such as ams1117 and it may waste some mili Ampere (not too much) and you certainly have a microprocessor and you should check data sheet but consider 100mA for that in worst case.
to count all of them the answer is YES

Sensors don't usually require that much current and a usb port should be able to handle 4 leds and the MCU without a problem.  If you are using an Apple laptop it will disable the usb port temporarily if you draw too much current from it.  Some PC laptops probably do the same.


text:
lightshow project

Hello guys. I'm working on a little lightshow that has 3 extra feature's when i press the button. depending on the variable counter the lights should do something and it should message you that you found a feature. But my project does'nt work. it compiles fine on the tinkercad site but not everything works. The lights itself work but the button feature's dont. I don't know if my code is wrong or the wiring since its able to compile.
I expected that if i press the countbutton it counts up and when it reaches 6 it does the code in the if statement. However when i press the count up and or count down button according to the variable it needs to reach it doesn't do anything.
the code:
int time = 250;
int ledpins[] = {3, 6, 7, 4, 2, 5};
int amount = 6;
int countup = 11;
int countdown = 12;
int counter;
int timepressed = 4000;
float timerpressed = 0;

void setup()
{
  for (int pin = 0; pin < aantal; pin++)
    {pinMode(ledpins[pin], OUTPUT);}
   //alle leds worden door middel van de loop gedefinieerd als output
   //pin is eerst 0 dat is element 3 in de array. de counter heeft einde
   //nog niet en gaat verder tot de conditie bereikt is
   pinMode(countdown, INPUT_PULLUP);
  pinMode(countup, INPUT);
   Serial.begin(9600);
}

void loop()
{
  bool plus = digitalRead(countup);
  bool minus = digitalRead(countdown);
  delay(20);

  if (plus == LOW){
    counter++;
   if (counter > 10) counter = 0;
  }

  if (minus == LOW){
    counter--;
  }

//Easter egg nummer 1. 2 lights on.
if (counter == -2){
    digitalWrite(ledpins[1], HIGH);
    digitalWrite(ledpins[4], HIGH);
    Serial.print("Gefeliciteerd je hebt (1/3) easter egg gevonden!");
}
//Easter egg nummer 2. all lights off.
else if (counter == 6){
  digitalWrite(ledpins[0], LOW);
  digitalWrite(ledpins[1], LOW);
  digitalWrite(ledpins[2], LOW);
  digitalWrite(ledpins[3], LOW);
  digitalWrite(ledpins[4], LOW);
  digitalWrite(ledpins[5], LOW);
  Serial.print("Gefeliciteerd je hebt (2/3) easter egg gevonden!");
}
//Easter egg nummer 3. blink alternately after keeping the button pressed for 4 seconds.
else if (timerpressed >= timepressed){
  digitalWrite(ledpins[0], HIGH);
  digitalWrite(ledpins[1], HIGH);
  digitalWrite(ledpins[4], HIGH);
  digitalWrite(ledpins[5], HIGH);
  Serial.print("Gefeliciteerd je hebt (3/3) easter egg gevonden!");
 }

Okay an update on this post is a was able to make a couple of fixes. My code was keep getting stuck in the array loop for the leds. I've made it that it now only goes trough it once. Another thing i fixed was the wiring of the buttons since this wasnt correct. The only feature that isnt working right now is the keep the button pressed feature.

int tijd = 250;
int ledpins[] = {3, 6, 7, 4, 2, 5};
int aantal = 6;
int knopplus = 11;
int knopmin = 12;
int teller;
int indruktijd = 4000;
float timerdruktijd = 0;
int pin = 0;
int pin1 = 0;

void setup()
{
  for (int pin = 0; pin < aantal; pin++)
    {pinMode(ledpins[pin], OUTPUT);}
   //alle leds worden door middel van de loop gedefinieerd als output
   //pin is eerst 0 dat is element 3 in de array. de counter heeft einde
   //nog niet en gaat verder tot de conditie bereikt is
   pinMode(knopmin, INPUT_PULLUP);
  pinMode(knopplus, INPUT);
   Serial.begin(9600);
}

void loop()
{
  bool plus = digitalRead(knopplus);
  bool minus = digitalRead(knopmin);
  delay(20);

  if (plus == LOW){
    teller++;
   if (teller > 10) teller = 0;
  }

  if (minus == LOW){
    teller--;
  }

//Easter egg nummer 1. twee lichten aan.
if (teller == -2){
    digitalWrite(ledpins[1], HIGH);
    digitalWrite(ledpins[4], HIGH);
    Serial.print("Gefeliciteerd je hebt (1/3) easter egg gevonden!");
}
//Easter egg nummer 2. alle lichten uit.
else if (teller == 6){
  digitalWrite(ledpins[0], LOW);
  digitalWrite(ledpins[1], LOW);
  digitalWrite(ledpins[2], LOW);
  digitalWrite(ledpins[3], LOW);
  digitalWrite(ledpins[4], LOW);
  digitalWrite(ledpins[5], LOW);
  Serial.print("Gefeliciteerd je hebt (2/3) easter egg gevonden!");
}
//Easter egg nummer 3. knipper om en om na 4 seconden lang de -knop ingedrukt te houden
else if (timerdruktijd >= indruktijd){
  digitalWrite(ledpins[0], HIGH);
  digitalWrite(ledpins[1], HIGH);
  digitalWrite(ledpins[4], HIGH);
  digitalWrite(ledpins[5], HIGH);
  Serial.print("Gefeliciteerd je hebt (3/3) easter egg gevonden!");
 }

  for (pin; pin < 6; pin++)
  {digitalWrite(ledpins[pin], HIGH);
   delay(tijd);
   digitalWrite(ledpins[pin], LOW);}
  //loop voor volgorde heen.

  for (pin1; pin1 < 6; pin1++)
  {digitalWrite(ledpins[pin], HIGH);
   delay(tijd);
   digitalWrite(ledpins[pin], LOW);}
  //loop zelfde volgorde terug
}

"It doesn't work" is a poor problem description. We have to search your code for the possible problem and that get's way easier, when you give us a good description of the problem. So please answer the questions: What is actually happening depending on your actions? What did you expect to happen instead?

I agree with chrisl; however one problem I see is that you need to debounce the buttons, see https://www.arduino.cc/en/Tutorial/Debounce   … also try to write your comments and variable names in English, not Dutch (I understand since I'm Dutch too, but most people will not).

thank you guys for the comments. I changed it according to you guys feedback.

Can you also give us a sample of the Serial output (if there is any)?

Why do you have one button with internal pullup but the other not?

I have no serial output :/, and i have one button with the pullup because i was searching for a sketch to make a pressed button function. I tested the sketch itself and it was working so i tought merging it together with this project then it should work aswell.

One button has no connection to ground. Check that purple wire second from the right on the top half of the breadboard...

At which point in the program do you update timerdruktijd if the button you mean is pressed (which of the buttons should even be pressed to activate this)?


text:
number generator show wrong segments on 7 segment display
I created a program to show a random number on a 7 segment display. It shows a random number in the serial monitor but always shows the same segments 'a c d and g'. anyone know hopw to fix this without changing the base of the coding its for and exercise so i need to have most of the code like I wrote it.
int num_array[11][7] = {
  { 1, 1, 1, 1, 1, 0, 1 }, // 0
  { 0, 1, 1, 0, 0, 0, 0 }, // 1
  { 1, 1, 0, 1, 1, 1, 0 }, // 2
  { 1, 1, 1, 1, 0, 1, 0 }, // 3
  { 0, 1, 1, 0, 0, 1, 1 }, // 4
  { 1, 0, 1, 1, 0, 1, 1 }, // 5
  { 1, 0, 1, 1, 1, 1, 1 }, // 6
  { 1, 1, 1, 0, 0, 0, 0 }, // 7
  { 1, 1, 1, 1, 1, 1, 1 }, // 8
  { 1, 1, 1, 0, 0, 1, 1 }, // 9
  { 0, 0, 0, 0, 0, 0, 0 }
};  //OFF

int buttonState = 0;
const int button = 12;
int randVal;
bool pressVal;
void num_Write(int);
void setup() {
  Serial.begin(9600);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(button, INPUT);
}

void loop() {
  buttonState = digitalRead(button);
  if (buttonState == LOW) {
    turnOff();
    pressVal = false;

  }
  else
  {
    if (pressVal == false)
    {
      int pin = 2;
      for (int i = 0; i < 7 ; i++)
      {
        digitalWrite(pin++, num_array[11][i]);
      }
      randVal = rand() % 10;
      pressVal = true;
    }
    Serial.println(randVal);
    if (randVal == 0)
    {
      void zero();

    }
    else if (randVal == 1)
    {
      void one();

    }
    else if (randVal == 2)
    {
      void two();

    }
    else if (randVal == 3)
    {
      void three();

    }
    else if (randVal == 4)
    {
      void four();

    }
    else if (randVal == 5)
    {
      void five();

    }
    else if (randVal == 6)
    {
      void six();

    }
    else if (randVal == 7)
    {
      void seven();

    }
    else if (randVal == 8)
    {
      void eight();

    }
    else
    {
      void nine();

    }
  }
}

void zero()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[0][j]);

  }
  delay(250);
}

void one()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[1][j]);

  }
  delay(250);
}

void two()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[2][j]);

  }
  delay(250);
}
void three()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[3][j]);
  }
  delay(250);
}
void four()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[4][j]);

  }
  delay(250);
}
void five()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[5][j]);

  }
  delay(250);
}
void six()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[6][j]);

  }
  delay(250);
}
void seven()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[7][j]);

  }
  delay(250);
}
void eight()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[8][j]);

  }
  delay(250);
}
void nine()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[9][j]);

  }
  delay(250);
}
void turnOff()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[10][j]);
  }
  delay(250);
}

Does your code really compile with all these forward declarations inside a function? Also very important: digitalWrite(pin++, num_array[11][i]); cannot work. The first dimension of num_array has only 11 elements. The element with the index 11 would be the 12th. So this is reading some data outside of the array.

yes i saw that and changed it already but the mlain problem is still the same. And i changed the code to look more like the one posted underneath here

@chrisl: ("Does your code really compile with all these forward declarations inside a function?") Yes, that's the Arduino IDE: generating a main() and function declarations.

@DataFiddler I just wondered, if it is ok to declare functions inside another function. I have seen this with other languages but not with C/C++ yet

@chrisl: Now I see your concern. A declaration inside a function is accepted without error.
But it won't work as as function call, as obviously intended.

Note, this is not an answer to your question, but I like to show some programming improvements, making your sketch  much shorter and easier to maintain.
Instead of having all functions one, two, etcetera, use a parameter to pass the number. So you get this: (I couldn't test it as I don't have an Arduino IDE at hand). Also you can use a for loop in the loop function to set the output pins.
int num_array[11][7] = {
  { 1, 1, 1, 1, 1, 0, 1 }, // 0
  { 0, 1, 1, 0, 0, 0, 0 }, // 1
  { 1, 1, 0, 1, 1, 1, 0 }, // 2
  { 1, 1, 1, 1, 0, 1, 0 }, // 3
  { 0, 1, 1, 0, 0, 1, 1 }, // 4
  { 1, 0, 1, 1, 0, 1, 1 }, // 5
  { 1, 0, 1, 1, 1, 1, 1 }, // 6
  { 1, 1, 1, 0, 0, 0, 0 }, // 7
  { 1, 1, 1, 1, 1, 1, 1 }, // 8
  { 1, 1, 1, 0, 0, 1, 1 }, // 9
  { 0, 0, 0, 0, 0, 0, 0 }
};  //OFF

int buttonState = 0;
const int button = 12;
int randVal;
bool pressVal;

void num_Write(int);
void digit(int value);

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

  for (int pin = 2; pin <= 8; pin++)
  {
    pinMode(pin, OUTPUT);
  }

  pinMode(button, INPUT);
}

void loop() {
  buttonState = digitalRead(button);
  if (buttonState == LOW) {
    turnOff();
    pressVal = false;

  }
  else
  {
    if (pressVal == false)
    {
      int pin = 2;
      for (int i = 0; i < 7 ; i++)
      {
        digitalWrite(pin++, num_array[11][i]);
      }
      randVal = rand() % 10;
      pressVal = true;
    }
    Serial.println(randVal);
    if ((randVal >= 0) && (randVal <= 9))
    {
      digit(randVal);
    }
  }
}

void digit(int value)
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[value][j]);
  }
  delay(250);
}

void turnOff()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[10][j]);
  }
  delay(250);
}

You can also remove turnOff if you treat it like digit 10 but that is not so clear (or put the implementation of digit to another function and call it from digit and turnoff.
To solve your problem, print the values of each pin to the serial monitor. If they are correct, there is a problem in your circuit. If they are incorrect, there is a problem in your sketch. In the latter case, add more print statements until you found the exact problem.
Update

Fixed void forward declaration to function call (see comment of chrisl)

If the digit function is never called, it means:

((randVal >= 0) && (randVal <= 9)) is false, however, that is not possible since it is initialized to 0 and with the rand function it gets always values between 0 to 9.
pressVal is always TRUE.

So check the value of pressVal, also add (lots of) print statements, especiallya after each if and else so you know exactly the flow of your sketch. You will see it's very easy to find the error. If you pinpoint the problem to a digitalRead that is not the expected value, THAN there is high likely a problem with your circuit (a button that is never going to be LOW or HIGH). In that case, you probably forgot a pullup/pulldown resistor.

Tnx for the feedback, will try to implement this seems alot neater than my coding. any idea how it would come that the wrong segments light up?

Not sure, I would follow the tip at the end, add more print statements to be sure that the sketch is ok, and if not, check the circuit.

So i tried finding the source of my problem and it never goes to  this part of the codevoid digit(int value) {   int pin = 2;   for (int j = 0; j < 7; j++) {     digitalWrite(pin++, num_array[value][j]);   }   delay(250); }

Did you remove the void in void digit(randVal); inside the loop function? Because that is wrong, since you don't want a forward declaration of a function there.

@chrisl I should have removed it (which I did now), probably you refer to that. And you're right, copy/paste error (having no Arduino IDE at hand). Thanks for the notification.

I updated my answer to give some more tips regarding the uncalled function.


text:
Extract binary numbers from infrared sensor that uses I2C bus
I have an infrared sensor(OTI 301) which in order to display the desired temperature I need to apply a formula that depends on 3 binary numbers extracted from the sensor itself. I have tried different approaches but no success yet to extract these binary numbers. Please see link for the data sheet of the sensor where you can see useful information regarding the formula and the binary numbers. https://drive.google.com/file/d/1XMRDCNzY3fn0q6lkGejs5D-pqksfRuZ8/view also here is the code I have tried in the Arduino IDE. Also, attached picture are the needed commands to extract the data from the second data sheet, https://drive.google.com/file/d/1mmdkHkNbwC5VgQxGMrq07XolajNvgBkN/view.
#include <Wire.h>
byte val[2] = {0x20,0x80};
void setup() {
Wire.begin(0x20);        // join i2c bus (address optional for master)
Serial.begin(9600);  // start serial for output
}

void loop() {

  //master writter
  Wire.beginTransmission(0x20); // transmit to device
  Wire.write(val,2);
  //Wire.write(x);              // sends one byte
  Wire.endTransmission();    // stop transmitting

  //master reader
  Wire.requestFrom(0x20, 6);    // request 6 bytes from slave device

  while (Wire.available()) { // slave may send less than requested
  Serial.println("H");
  char c = Wire.read(); // receive a byte as character
}

delay(500);
}

Try making your write data just 1 byte long, with value 0x80.

0x20 is the shifted address (to make room for the read/write bit). Arduino expects the unshifted address, i.e. 0x10.

There are likley two problems:

An invalid device address is used. The device address is 0x10 and the Arduino Wire library expects it that way (and not in the shifted version with read/write bit).
Your code uses two separate transactions, however the datasheet specifies a single transaction with a repeated START condition for separating the write and read part.

So an improved version looks like so:
#define DEVICE_ADDRESS 0x10

void loop() {
    Wire.beginTransmission(DEVICE_ADDRESS);
    Wire.write(0x80);  // readout command
    Wire.endTransmission(false); // stop sending without ending transaction (repeated START)
    Wire.requestFrom(DEVICE_ADDRESS, 6); // request 6 bytes
    uint8_t data[6];
    for (int i = 0; i < 6; i++) {
        data[i] = Wire.read();
    }
}


text:
How to use ATtiny pins that are usually 'reserved' for chip programming?
How to program an ATtiny45 to use the pins 1, 5, 6, 7 (i.e. PB5, PB0, PB1, PB2) as input or output?
pinMode(5, OUTPUT);
pinMode(0, OUTPUT);
pinMode(1, INPUT);
pinMode(2, INPUT);
digitalWrite(5, HIGH);
...

These pins are usually used to program the ATtiny itself, so how to avoid a conflict?
Of course, I could just avoid these 4 pins, but then as there are also pins for VCC and GND, there would be only 2 pins left: PB3, PB4!
Question: how to use the pins as input/output that are usually used for ATtiny programming?

Linked question:

Should I connect pins 1, 5, 6, 7 of the ATtiny to the programmer
Or should I connect pins 1, 5, 6, 7, as well as 8 and 4 (VCC and GND) of the ATtiny to the programmer?

If the second bullet is correct, when connecting VCC and GND, won't it make the ATtiny run the previously uploaded code?

Clue: They aren't reserved for programming. They double as the programming pins.

The ATTiny chips commonly used in Arduino-like boards, such as the Adafruit Trinket or the Digispark USB will usually have a bootloader which runs before your own code. The bootloader checks for a certain state on the USB port of the board, to see if something is waiting to write a new program to the chip.
The bootloader accepts new code from the host computer, if present, and writes it to a certain location in flash memory. If the bootloader does not find anything connected to the USB connector trying to load a new program, then it (the bootloader) starts executing from flash at the location where your program has been stored.
But, what if you want to write a new bootloader, or not have a bootloader? In that case, you can write new software using the MOSI, MISO, and SCK (clock) pins if the RESET pin is pulled to ground.
See:
http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf#page=151
In order to make use of all 6 non-power pins as I/O for the Trinket or Digispark, a "fuse" is set in the ATTiny chip which disables the RESET pin's normal purpose of holding the chip in reset. This means you cannot pull RESET to ground and load a program the normal way.
If the RESET pin is disabled, and the bootloader is not present, then there is another method for loading software, called "High Voltage Serial Programming". Not to worry, the "high" voltage is is about 12V.
See:
http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf#page=155
You can find schematics, or purchase kits/products that allow you to program an ATTiny chip in HV mode online. Many use the small 12V "A23" or "A27" batteries commonly found in RF remote control transmitters to get the 12V signal to put the chip in high-voltage programming mode.

this looks like an answer to OP's other question

Both seem to be related...

Thank you for your answer!

@Basj If this answers your question, please mark it.

You can just normally use all pins except for the reset pin (pin 0). When you want to program the Attiny, you just connect the programmer. It will reset the Attiny through the reset pin and put it into ISP programming mode. At that point your code hasn't run.
Note: If you want to program the Attiny while it still sits in its circuit, you have to be careful, that the connected circuit does not disturb the ISP communication. The safest way is to disconnect the Attiny from its circuit and then program it.

Also account for the ISP communication disturbing your connected circuit.

Just to be sure: when I use Arduino Uno as ISP programmer for an ATtiny, I usually connect pins 1, 5, 6, 7. Do I also need to connect VCC and GND of the ATtiny to VCC and GND of the Arduino Uno? If so, when connecting VCC and GND, won't it make the ATtiny run the previous code? (I updated the question at the end to include this remark).

Yes, you need to also connect GND and VCC. Unless your ATTiny project has it's own power-supply/batteries ( in which case you still need to connect GND). The programmer will pull the reset pin LOW, which will stop your original program from running and enter the ATTiny into "ISP mode".


text:
Somewhat Obfuscated Serial With SIM800L and Uno R3
I am successfully communicating with my SIM800L from my UNOR3 aside form some errors. But the biggest problem is with the serial monitor.
Responses from the SIM800L are somewhat obfuscated in that some characters are randomly wrong. See a snippet below:
Initializing...

OK

+C⸮T'⸮⸮b⸮j

OK

88l4110068165694746f

O⸮

+CQEG:Y⸮⸮H⸮⸮*⸮⸮C⸮
ERROR
⸮> H⸮⸮*⸮⸮
F⸮ROR
H⸮⸮
ERRO
H⸮⸮*⸮⸮

My code is also below.
#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM800L
SoftwareSerial mySerial(11,10); //SIM800L Tx & Rx is connected to Arduino #3 & #2

void setup()
{

  pinMode(2, INPUT);
  pinMode(3, OUTPUT);
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(115200);

  //Begin serial communication with Arduino and SIM800L
  mySerial.begin(115200);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Once the handshake test is successful, it will back to OK
  updateSerial();
  mySerial.println("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
  updateSerial();
  mySerial.println("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
  updateSerial();
  mySerial.println("AT+CREG?"); //Check whether it has registered in the network
  updateSerial();
  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  mySerial.println("AT+CNMI=1,2,0,0,0"); // Decides how newly arrived SMS messages should be handled
  updateSerial();
  mySerial.println("AT+CMGS=\"+447518103652\"");//change ZZ with country code and xxxxxxxxxxx with phone number to sms
  updateSerial();
  mySerial.print("System on!"); //text content
  updateSerial();
  mySerial.write(26);

  delay(1000);
}

int milli = millis();
void loop()
{
  if (digitalRead(2) == HIGH) {
    digitalWrite(3, HIGH);
  mySerial.println("AT+CMGS=\"+447518103652\"");//change ZZ with country code and xxxxxxxxxxx with phone number to sms
  updateSerial();
  mySerial.print("Button Pressed!"); //text content
  updateSerial();
  mySerial.write(26);
  } else {
    digitalWrite(3, LOW);
  }

  if (milli <= millis() - 500) {
    updateSerial();
    milli = millis();
  }
}

void updateSerial()
{
  //delay(300);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

The SIM800L runs off a separate power supply with a decoupling cap of 100n and the grounds are commoned.

Which SIM800L board are you using? What is the wiring and wire length between the uno and the module? Do you have level shifting in place for a possibly necessary 3.3V <-> 5V conversion?

Its a coreboard, one jumper wire and internal breadboard connections. I don't know what you mean by that unless you mean stepping down the serial voltage which did not help.

Do you have a link to the SIM800L board you're using?

I don't but it looks like this https://www.google.com/url?sa=i&source=images&cd=&cad=rja&uact=8&ved=2ahUKEwjHgIL9zO_lAhXpAmMBHQhiCqEQjhx6BAgBEAI&url=https%3A%2F%2Fwww.banggood.com%2FSIM800L-GSM-GPRS-Module-Board-MicroSIM-Transfer-Card-Core-Board-Quad-band-p-1086519.html&psig=AOvVaw0LLO-qboau_2vsBH7ne9uo&ust=1574023590691357

So what voltage do you give as VCC and what level shifting circuitry are you using? This is just the bare module with a capacitor, you need to directly feed it with the necessary voltage of 3.4 to 4.2V and need at least level shifting from 5V to the target VCC.

It takes 3.8 v from my external power supply

Here is a good documentation: https://lastminuteengineers.com/sim800l-gsm-module-arduino-tutorial/ --
Did you add a voltage divider to the RX pin?
If Arduino drive 5 Volt to the module's pin, the module might be destroyed.
The module has an automatic baud rate detection, so 115200 baud should be OK.
Do you configured your terminal with 115200 baud for the serial communication?
While sending, the Software Serial switches off all interrupts to make the micro clock more accurate. That might distort a timer interrupt for the hardware serial (but I don't really know, whether it needs one).
You changed the pins 2 and 3 for software serial (as from the example) to SoftwareSerial mySerial(11,10); Did you add the connections to the right pins. (RX?? <--> TX??)?
And last but not least. The axample uses 9600 baud for both serial interfaces. Perhaps your decision 115200 is too high.

I originally followed that, so tried changing the pins and baudrate which helped because with 9600 the chip wouldn’t respond and with the voltage divider from that tutorial I had the same issue.

@JamesConway Please check if you connected pin 11 of the arduino  to the TX pin of the module and pin 10 to the RX pin of the module. And check if you set your Serial Terminal in the Arduino ID to 115200 baud as you have configure the  hardware serial for 115200 baud too. By looking at the Serial output  I would say you have problems with the connection from the uno to the PC. So the baud thing is the most probable.


text:
while(1) inside if conditional
if (!MDNS.begin("esp8266")) {
    Serial.println("Error setting up MDNS responder!");
    while (1) {
      delay(1000);
    }
  }

I know this will result in an infinite loop if the if conditional is never satisfied, however I was wondering if this code would still result in an infinite loop if say, after 3 iterations the if conditional is satisfied?
Or if something like:
while(!MDNS.begin("esp8266")) {
   delay(1000);
}

is different?
Code from: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266mDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino (line 58)

why do you feel that the if condition could be satisfied more than once?

i don't. im saying, say in the first iteration it isn't. while loop enters. then what happens? is there any scenario in which we leave this loop? are if(condition) { while(1) } the same as while(conditional) { }

If it isn't then the while loop isn't entered.  The first time the if statement is true then you get to the while loop and the code is dead there forever.  It's very different from the second thing you wrote.  In that while loop it is checking to see if that begin function returns true, not checking that 1!=0

i guess the reason i was asking is because i don't see why the original author wrote it that way unless there was some trickery that i wasn't aware of. basically, they are just halting everything indefinitely which seems odd to me rather than triggering a device restart.

you are somehow missing the fact that the code is just example code that shows how to code a web server ... recovery code would add irrelevant routines

This is likely a case where the original code needs to be inspected to understand the purpose of the infinite loop.  In the original code we see this:
  if (!MDNS.begin("esp8266")) {
    Serial.println("Error setting up MDNS responder!");
    while (1) {
      delay(1000);
    }
  }
  Serial.println("mDNS responder started");

Here, it can be inferred the infinite loop is used to preserve the error message on the serial monitor.  By doing so prevents subsequent messages from announcing the Domain Name Server has started.  Which may confuse the user.
As mentioned in other answers, infinite loops are often used to purposely reset a processor.  However, this approach depend on an actively running watch dog feature.  A feature that is not normally active or even supported in the Arduino development environment.  Perhaps because the watch dog feature is considered an intermediate to advanced topic.

In the first case, the first time, that the outer if statement becomes true, the code will go into the while(1) loop and will be stuck there forever.
The second code is different, since the while loop will check at each start of it's iteration, if the condition is still met. If not, it will exit, so not necessarily an infinite loop.

Going into an infinite loop, if something fails to initialize is often done in the microcontroller world, especially when initializing external hardware. A reset loop (restarting until it works) is mostly not fitting there, because often it is not just waiting for a resource to become free. Often this is used for serious problems, for example external hardware not being there or functioning. Imagine trying to use an external GPS chip, but the chip is not there. It should be there, since the device is build this way. Why should a reset loop be better here? The problem won't get away with time. Or imagine, that the initialization fails, because the GPS chip is broken. Trying to interface such a broken chip repeatedly might break even more things. Either way, someone has to look at this, to fix the problem. It will not go away by itself.
I would say, that the failed initialization in the library above is such a situation.


text:
8 digit 7 segment display issues
I've been trying to follow a few tutorials on how to get the 7 segment to display simple output but none seem to work 100%.
It starts out fine. It increments the number across the screen and then writes 8s to all of them and then reverses. After a few loops however it starts to act weird. Here's a video link where it acts a bit weird (a few digits don't write correctly and fix themselves) and then at the end, it only displays half of the 8 digit display before it goes to 8s and crashes. https://youtu.be/LD_C7I_bGyc
Here's the code:
//We always have to include the library
#include "LedControl.h"

// pin 4 is connected to the DIN pin
// pin 2 is connected to the CLK pin
// pin 3 is connected to the CS pin
// 1 as we are only using 1 MAX7219
LedControl lc = LedControl(4, 2, 3, 1);

void setup(){
    // the zero refers to the MAX7219 number, it is zero for 1 chip
    lc.shutdown(0, false);// turn off power saving, enables display
    lc.setIntensity(0, 0);// sets brightness (0~15 possible values)
    lc.clearDisplay(0);// clear screen
}

void loop(){
    // numbers 7 to 0
    for (int a = 0; a < 8; a++){
        lc.setDigit(0, a, a, false);
        delay(100);
    }
    delay(1000);
    // display number 8 on all segments
    for (int a = 0; a < 8; a++){
        lc.setDigit(0, a, 8, false);
        delay(100);
    }
    delay(1000);

    for (int a = 8; a >= 0; a--){
        lc.setDigit(0, a, a, false);
        delay(100);
    }
}

Hardware:
   Arduino Uno: https://www.jaycar.com.au/duinotech-uno-r3-development-board/p/XC4410
   8 digit display: https://www.jaycar.com.au/8-digit-7-segment-display-module/p/XC3714
At this stage it's hard to tell if it's a hardware issue or if it's setup related. If someone could please give me some insight or maybe run it if they have the same hardware that would be fantastic.
Thanks!

You should switch your display on. Your setup() call to lc.setIntensity(0, 0) turns the display intensity to zero, try setting it to 15.

That's just the brightness. It was originally 15 during the day but at night I turned it down because it was too bright.

I wonder if you're timings are too fast. There's timing values in the datasheet at https://datasheets.maximintegrated.com/en/ds/MAX7219-MAX7221.pdf try slowing everything down a bit.

for (int a = 8; a >= 0; a--){ -- Why do you start with 8 and not with 7. The forward version go to 7 a < 8;. BTW: I enjoyed the question, because of the video. Cool Idea. ;-)

@Dougie you were pretty close. I posted an answer to the fix as it was actually the ground wire not being stable. I had previously changed all the wires that control the 8 digit however I never thought to change the power and ground wires to the board. Not having a stable ground wire would have messed up the communication and affect the timings a lot.

@PeterPaulKiefer the video was the only way I could think to show people to make them believe how weird it was acting :)

This was an unexpected result. @Dougie was pretty on to it. I didn't know how to adjust the timings as I was pretty sure the library took care of it, so the only thing I could think of was to redo all the wiring again. That's when I noticed that the ground wire pin into the board was half sticking out.
In the video you can see the ground pin at the top right. So it was making a connection (otherwise the whole thing wouldn't work), but after replacing the wire it runs fine. So that would have messed up the timings if the connection was unstable.

Well, it might have changed the values recognized by the chip. If you lose ground (no pun intended) the reference level is lost. A "low" (bit value 0) might be read as "high" (bit value 1) or vice versa. The timing will not change because of a missing ground connection.

I'm not an expert at this, but my guess was that the Arduino was sending the messages but since it wasn't grounding properly it was cutting out and therefore getting mixed messages during each timing round.

@the bussybee, I'll need to do some research as to how ground actually impacts it as I thought it just completed the circuit.

The last loop exceeds the limits of 8 Digits. You iterate 9 times (0-8).
   for (int a = 7; a >= 0; a--){
        lc.setDigit(0, a, a, false);
        delay(100);
    }

This is almost certainly the problem. (voted.) Array out-of-bounds problems cause lots of strange symptoms.

Annoyingly that didn't fix it. I'm guessing if it was then it would crash on the first main "loop" but it runs for a while before freaking out.


text:
How fast should I be able to write to AT45DB321D flash memory?
I checked the AT45DB321D datasheet and it says it operates at either 66 MHz oder 33 MHz. Both of these speeds are higher than what an Arduino Nano supports (my google fu fails me here, but according to the Arduino SPI doc it's probably on the order of 4 MHz).
According to the datasheet

Data can be clocked in from the input pin (SI) into either buffer 1 or buffer 2. To load data into the standard DataFlash buffer (528 bytes), a 1-byte opcode, 84H for buffer 1 or 87H for buffer 2, must be clocked into the device, followed by three address bytes comprised of 14 don’t care bits and 10 buffer address bits (BFA9-BFA0). The 10 buffer address bits specify the first byte in the buffer to be written. [...] Data will continue to be loaded into the buffer until a low-to-high transition is detected on the CS pin.

Which means to write a single byte I would need

1 opcode byte
3 address bytes
1 data byte

totaling 5 bytes or 40 bits which at 4 MHz yields 10 µs.
My code, as below, yields roughly 48 µs per byte (outputs a duration of ~12380 µs for transfering 256 bytes). I'm using the DataFlash library.
#include <SPI.h>
#include "DataFlash.h"

static const int csPin    = 10;
static const int resetPin = 8;
static const int wpPin    = 7;

DataFlash dataflash;

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

  SPI.begin();

  dataflash.setup(csPin, resetPin, wpPin);
  dataflash.begin();

  long start = micros();
  dataflash.bufferWrite(0, 0);
  for(int i = 0; i <= 255; i++) {
    SPI.transfer(i);
  }
  long afterBuffer = micros();

  Serial.print("Writing 256 values to buffer: ");
  Serial.println(afterBuffer - start);
}

void loop()
{
  // nothing
}

It's very likely I'm missing something, but especially if I want to transfer larger chunks of data at once I'd like to speed up that process a bit. Creating a 256 byte buffer and writing it all at once
// outside time measurement
uint8_t buffer256[256];
for(int i = 0; i <= 255; i++) {
  buffer256[i] = i;
}
// inside time measurement
SPI.transfer(buffer256, 256);

takes roughly the same time.
tl;dr: Is everything working correctly/what am I doing wrong? How can I speed up writing to a flash chip using an Arduino Nano?

The fastest that SPI can work at is F_CPU/2, so for a 16MHz Arduino that's 8MHz.

I would attach an oscilloscope and measure; that's the best way to see whether my assumptions about clock frequencies and times are right.

"Data will continue to be loaded into the buffer until a low-to-high
  transition is detected on the CS pin."

The dataflash.bufferWrite command writes the opcode and address bytes and then in the for loop you write 256 data bytes. The data bytes are written at once, without preceding each single one with the opcode and the address. (So it does already what you want to do.)
It doesn't matter whether you write the byte at once or each with a single SPI write. SPI can only send them sequentially. And the initial opcode and address is only send once with the dataflash.bufferWrite command.
BTW: There are two buffers to write to 1 and 2. So I'm curious why the command dataflash.bufferWrite(0, 0); works. IMHO that should be dataflash.bufferWrite(1, 0); or dataflash.bufferWrite(2, 0);.
You also not start the internal writing to the pages. There is no command e.g. dataflash.bufferToPage(1, 7);. The data are only transfered into the flash's buffer.
Because data is not written into a memory page, you'll lose it, if you switch off the power.
UPDATE
I fear I understood your question not completely. As I now see, you wondered why you need 48 µs in average for 256 Bytes when the SPI Bus is driven with 4MHz.
I looked a little in the codes and docs. And that's what I found:
The DataFlash lib selects a different Clock divider:
/* Setup SPI */
SPI.setDataMode(SPI_MODE3);
SPI.setBitOrder(MSBFIRST);
SPI.setClockDivider(SPI_CLOCK_DIV2);

SPI_CLOCK_DIV2 results after some computation to a frequency of Fosc/2. The computation are very difficult to follow, because they use an 8 bit number which is divided into 2 nibbles each of them defines a part of a register content. But I'm quite sure the result is Fosc/2. But that would result in a clock frequency of 8 MHz. That can not explain your observed timings.
BTW: There is also in interesting deprecation note about setting the clock speed this way. ;-)
  // This function is deprecated.  New applications should use
  // beginTransaction() to configure SPI settings.
  inline static void setClockDivider(uint8_t clockDiv) {
    SPCR = (SPCR & ~SPI_CLOCK_MASK) | (clockDiv & SPI_CLOCK_MASK);
    SPSR = (SPSR & ~SPI_2XCLOCK_MASK) | ((clockDiv >> 2) & SPI_2XCLOCK_MASK);
  }

But then I saw another thing that could be a problem. There are to single value transfer functions. One for bytes (uint8_t) and one for integers (uint16_t). Your count variable is an integer so the two byte transfer method is used, resulting in two byte per transfer and therefor 512 bytes. But that also no explanation for the observations. And writing buffers works only with uint8_t[] so ??.
What else could have happened?
The MCU could be clocked by a lower frequency then 16MHZ. I think there are fuses that can be configured to reduce the master clock speed for using the MCU with lower voltage (like 3.6 Volt).
The missing beginTransaction / endTransaction (DataFlash doesn't use this) of the SPI bus could have impact on the interrupts which could distort the timing. (But that's a very wild guess ;-))
The observation that, transferring twice the amount of data with the single int transfer method does take roughly the same time than the buffered method gives us a hint, that possibly the SPI speed is not the problem.
In the function dataflash.bufferWrite(0, 0); there is e.g. a wait function
waitUntilReady(); that could cause a long delay of ~12 milli seconds. You can easily try that, by taking the dataflash.bufferWrite(0, 0); out of the timing.
void DataFlash::waitUntilReady()
{
    while(!isReady()) {};
}

uint8_t DataFlash::isReady()
{
    return status() & AT45_READY;
}

uint8_t DataFlash::status()
{
    uint8_t status;
    reEnable();     // Reset command decoder.
    SPI.transfer(DATAFLASH_STATUS_REGISTER_READ);
    status = SPI.transfer(0);
    disable();
    return status;
}

You're right, bufferWrite(0, 0) works because internally it's (among other things) SPI.transfer(bufferNum ? DATAFLASH_BUFFER_2_WRITE : DATAFLASH_BUFFER_1_WRITE);. Also, I am aware of the transfer of the buffer to the memory page, but that's outside the scope of this question (and takes approx. 50 µs as well ;-).

Thank you. I assumed something like that, but was not sure. I read the question a second time and now I hope, I see the problem. I'll update the answer.

@Raketenolli I've updated the answer.

Sorry for not getting back to this sooner, and now I'm wondering whether I changed anything back then that I now forgot about. I am now observing between 660 and 670 µs consistently for the entire writing operation, which means roughly 2.6 µs per byte. The SPISettings speedMaximum parameter only has an effect when set to less than 8000000, where the duration will increase to 940 µs (and then in steps to 1520, 2500 and 4560).


text:
Get data from Bluetooth scale
I am trying to get data from this type of scale
https://acaia.co/products/pearl. It does not show up under discover-able Bluetooth devices on a computer or phone, but it does have an app which it connects to automatically when turned on; the app can then display the weight in real time. This is my first time working with Bluetooth devices and am unsure as to how it is connecting to the app without showing up on other devices. Any information as to what is going on and possibly steps in the right direction would be greatly appreciated.

How is this connected to Arduino? Do you want to use one to communicate with the scale?

If you are sniffing with Microsoft Windows 10 you may want to stop.  Windows 10 is not a great platform to develop on.  It assumes many thing and does not tell the user about the assumptions.  As of late (fall of 2019) Windows 10 will stop connecting to certain BlueTooth devices if Windows 10 thinks the devices are not safe to connect to.

@chrisl yes, sorry the plan is to use an uno with a bluetooth module. We just want to have a way of getting the current weight on the scale

What you need to do is do some bluetooth sniffing to find out how the device is communicating with the phone. Here is a good article on doing that : http://nilhcem.com/iot/reverse-engineering-simple-bluetooth-devices