text:
Digital to Analog converter with DAC5311, Any suggestion?
I made my DAC code with DAC5311 and Arduino Uno.
I think it has no problem, but it doesn't work well. Just print 0.(I use an oscilloscope.)
I don't know where has the problem. Please give me any suggestion.
#include <SPI.h>
#include <math.h>
#define pin_CS 10
#define pin_MOSI 11
#define pin_SCLK 13
#define max_VOLT 5

void setVoltage(float voltage){
  if (voltage < 0) voltage = 0;
  if (voltage > max_VOLT) voltage = max_VOLT;
  uint16_t temp = int(voltage * pow(2, 8) / max_VOLT);
  temp = temp << 6;
  uint8_t upper = temp >> 8;
  uint8_t lower = (temp & 0xff);
  digitalWrite(pin_CS, LOW);
  SPI.transfer(upper);
  SPI.transfer(lower);
  digitalWrite(pin_CS, HIGH);
}

void setup() {
  Serial.begin(9600);
  pinMode(pin_CS, OUTPUT);
  pinMode(pin_MOSI, OUTPUT);
  pinMode(pin_SCLK, OUTPUT);
  SPI.begin();
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  digitalWrite(pin_CS, HIGH);
}

void loop() {
  setVoltage(5);
  delay(10);
}

a statement, it doesn't work well, has no meaning  ... I use an oscilloscope is also meaningless ... please explain what you expected to happen, what actually happened and what you did with the oscilloscope

Sorry, I'm not good at English. So it might be not clear. The point is that I want to set  voltage 5, but the output of DAC5311 is zero. And I check the output with oscilloscope.

now, that is clear ... please edit your question ... your english is just fine ... is your oscilloscope functioning correctly and are the controls set correctly? ... double check the output using a voltmeter

Classical +/- 1 problem
If you do this calculation by hand uint16_t temp = int(voltage * pow(2, 8) / max_VOLT);
you will get temp=256 and this is a value you can not convert with a 8 bit DAC.
Try uint16_t temp = int(voltage * (pow(2, 8)-1) / max_VOLT); instead.
(or event better for a µC uint16_t temp = (uint16_t) (voltage * (255 / max_VOLT));)

I revised it, but it was not still working. ㅜㅜ

So please try SPI_MODE1 or SPI_MODE3
(the device expects the valid bit on the falling clock phase)


text:
How can we get a timer interrupt at a specific time or date?
How can we get a timer interrupt at a specific time or date?
For example: I want to make a project with an Uno and I'm using sleep mode and the wake-up source is timer2, as per the ATMega328p datasheet.
I want to turn on an LED, for example every day at 3pm, and the chip is in sleep mode on other times of the day.
So, how can I set the timer?
I think I have to use CTC mode of timer2 and set the OCR amount but I'm not sure how to do it.
There's a project on (Link) this link on the Arduino site that is perfect for this project, but when I compile it, it gives me an error saying that it can't be compiled for the Uno.

Use an RTC chip. The Arduino timers have no concept of real time, only relative time, and that usually over very short periods.

Incidentally, that project uses an RTC that is built in to some of the more advanced (ARM) chips.

16.38 ms is the longest period you can get out of Timer 2. And 4.19 s  is the longest you can get out of any timer of the Uno.

source: Stack Exchange

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

sort: votes


text:
How to use attachInterrupt() in ATtiny85 with Arduino IDE?
It's possible use external interrupts/attachInterrupt() with the ATtiny85 when I program with Arduino IDE?
If is possible, how many inputs (for external interrupts) the ATtiny85 have and which are they?
Someone have an example code?

The ATTINY 85 doesn't have external interrupts.  You'll have to use pin change interrupts instead.

Except... PB2 has INT0...

Darnit.  I just looked at the spec sheet and didn't see one listed.

Pin PB2 is the only pin that has a real external interrupt.  This is INT0.
Whether you can use attachInterrupt(0, ...) or not is entirely down to whether it is implemented in the core that you are using.

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


text:
Http request in interrupt esp8266 not working
So i have this code that whenever i click a button a interrupt starts.
In this interrupt i want to do a get request to a webserver.
The thing is seperate the code, the interrupt code works and without an interrupt the http request also works.
But when i put this together it doesn't.
Does anybody have an idea why this doesn't work?
// Libraries
#include <ESP8266HTTPClient.h>
#include<ESP8266WiFi.h>

char ssid[] = "";
char pass[] = "";

int ledpin = 5; // D1(gpio5)
int button = 4; //D2(gpio4)
int buttonState=0;

ICACHE_RAM_ATTR void ISR() {
  static unsigned long last_interrupt_time = 0;
  unsigned long interrupt_time = millis();

  if (interrupt_time - last_interrupt_time > 200)
  {
      Serial.println("Drukknop ingedruk");
      Serial.println("Sending message to server");
       if (WiFi.status()==WL_CONNECTED)
      {
        HTTPClient http;
        String url="<httpurl>";
        http.begin(url);
        http.addHeader("Content-Type","text/plain");
        int httpCode=http.GET();
        Serial.println(httpCode);
        String payload=http.getString();
        Serial.println("While sending I received this from server : "+payload);
        http.end();
      }
      else
      {
        Serial.println("Internet Problem!");
      }
  }
  last_interrupt_time = interrupt_time;
}

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid,pass);

  while(WiFi.status() !=WL_CONNECTED)
  {
    delay(500);
    Serial.println("Waiting for connection");
  }

  Serial.println("Connected...");
  delay(1000);
  if (WiFi.status() ==WL_CONNECTED)
  {
    Serial.println("Wi-Fi Connected!");
  }
  delay(5000);
  Serial.println("ok");
  pinMode(button, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(button), ISR, RISING);

}
void loop() {

}

Doing something as complex as a HTTP request in an interrupt is a very very silly idea. Instead set a flag in the interrupt routine and examine that in the main loop() function to perform your HTTP request.

Thank you, this works

@ThomasVanRaemdonck if it works (and it should) please accept Majenko's answer as correct; that helps other users see the correct answer and gives Majenko credit.


text:
How to connect naked camera from mobile phone to Arduino Uno
Okay, guys. I have this 3 cameras(middle from the iPhone 6s, 2 at the side I found, and I think there are from modern phone). I need some information how to connect Arduino Uno to them. I know c/c++, assembler, but noob in microcontrollers, if this knowledge can come useful.

No chance. Sorry. Think again.

About fingerprint sensor, but the answer is fitting also this question: https://arduino.stackexchange.com/questions/71753/can-i-connect-a-android-phone-fingerprint-scanner-to-arduino-or-a-raspberry-pi

sounds like a call, thx

I don't think an UNO could do anything useful with any of those cameras

Can u offer something else?

https://randomnerdtutorials.com/esp32-cam-video-streaming-face-recognition-arduino-ide/

This is a demo code with a proximity sensor on how to Trigger the camera of your cell Phone by Arduino. You can make Ultrasound Motion sensor or PIR sensor to work as a Motion sensing anti theft Camera system. * It's just an Idea , The Sky is the Limit */
int trig = 13;
void setup() { pinMode(trig,OUTPUT); Serial.begin(9600); // initialize serial communication at 9600 bits per second:
}
void loop() // the loop routine runs over and over again forever:
{ int sensorValue = analogRead(A0); // read the input on analog pin 0: Serial.println(sensorValue); // print out the value you read: delay(1); /

You need either a memory extension for your UNO - projects like Arducam did this way back 2016 and then used an OV2640 module. If you want to develop something yourself these are the steps (hurdles) to take:

Get a datasheet of the camera
Design a circuit including

plug for Camera and a
memory module (min 512Kb)

Attach it to the UNO
Write a library/function module (see datasheet for details) and
bring it to life

My tip save ca. two years of your life and get for 6-8$ an ESP32cam
This will cost you enough of your time, but be much more rewarding


text:
Sending serial data to arduino, while an operation triggered from serial data is underway
I have this snippet of code:
 if (Serial.available())
 {
    /***** DEFINE MEASUREMENT MODE *****/
    String input = Serial.readString();
    if (input[0] == 'r' && interrupts_enabled == false)
    {
      if (input[1] == 'f')
      {
        full_mode = true;
        sensor_coord = 0;
      } else
        sensor_coord = input[2] - '0';  // r *SPACE* [0-7]

      select_sensor();

      pulse_counter = 0;
      TIMER1_clear();

      interrupts_enabled = true;
    } //first if ends here
    else if (input[0] == 'C' || input[0] == 'c')
    {
      interrupts_enabled = false;  //If the user types 'C' OR 'c', stop the measurement
    }
 }

So when i send 'rf' to the arduino, a measurement to all my sensors starts hapening indefinetely.
(There is another mode as well, typing 'r 0' will start an infinite measurement on the first sensor.)
When all the eight sensors, are measured, it will start from the beggining.
I wanted to be able to stop this operation when i typed a command in the serial.
This is why i addded the  else if (input[0] == 'C' || input[0] == 'c') portion.
So that, when the infinite measurement occurs and i press 'C', it is supposed to stop.
But it didn't work.
Not only that, but if i am in full mode and i then press another serial command, such as previously mentioned 'r 0'. , nothing happens as well.
So what i am asking is:
Is there a way to stop an operation triggered frmo serial that is underway?
And by stopping it, i mean from serial as well.
Perhaps, when an operation is uderway taht is triggered from serial, it cannot be stopped until the operation is finished?
Maybe it has to do something with when i have already typed 'rf' and sometime later i type 'C', maybe that 'C' is no longer on position input[0] of the serial buffer?
EDIT: This is the full code:
/***** CONSTANTS *****/
const int BAUD_RATE = 9600;
const int INTERRUPT_PIN = 3;
const int S0_PIN = 4;
const int S1_PIN = 5;
const int S2_PIN = 6;
const int OE_BAR_PIN = 22;
const int NUM_OF_SENSORS = 8;

/***** ANALOG CIRCUIT CONSTANTS *****/
const double CAPACITOR_VALUE = 400; //pF
const double GAIN_VALUE = 3.5222672065;
const double R_BIAS_VALUE = 98.7; //kΩ

/***** GLOBAL VARIABLES *****/
int number_of_samples = 500;
int sensor_coord;
boolean full_mode = false;

unsigned long overflows = 0;
unsigned long ticks = 0;
double period = 0;

//variables for determining if a resistance cannot be measured !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
unsigned long timestamp = 0;
unsigned long measurement_timeout = 5000;  //5 seconds is the timeout time
boolean sensor_corruption[8]; //each element of the array is the sensor info. If false, resistance is working. If it's true, resistance is open.
boolean ISR_unavailable = false; //this flag is raised, when the ISR does not run, because no signal comes from the circuit, because resistance is open circuit

//variables that get changed inside the ISR - thus are declared volatile!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
volatile int pulse_counter = 0;
volatile boolean interrupts_enabled = false;
volatile boolean measurement_finished = false;

void setup()
{
  attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), count_time_of_k_pulses, RISING);

  digitalWrite(OE_BAR_PIN, HIGH);
  pinMode(OE_BAR_PIN, OUTPUT);
  pinMode(S0_PIN, OUTPUT);
  pinMode(S1_PIN, OUTPUT);
  pinMode(S2_PIN, OUTPUT);

  TIMER1_init();

  Serial.begin(BAUD_RATE);
  while (! Serial);

  //Initializing all array elements to false!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  for (int i=0; i<=7; i++)
  {
    sensor_corruption[i] = false; // false means it's working ok. true means it's open-circuit (or cannot be read anyway)
  }
}

void loop()
{

  //CODE FOR SERIAL INTERFACE (RESISTANCE SELECTION)
  if (Serial.available())
  {
    /***** DEFINE MEASUREMENT MODE *****/
    String input = Serial.readString();
    if (input[0] == 'r' && interrupts_enabled == false)
    {
      if (input[1] == 'f')
      {
        full_mode = true;
        sensor_coord = 0;
      } else
        sensor_coord = input[2] - '0';  // r *SPACE* [0-7]

      select_sensor();

      pulse_counter = 0;
      TIMER1_clear();

      interrupts_enabled = true;
    } //first if ends here
    else if (input[0] == 'C' || input[0] == 'c') //not sure if it's case sensitive, but just to make sure i added both capitals and lower-case
    {
      interrupts_enabled = false;  //If the user types 'C' OR 'c', stop the measurement
    }
  } //Serial.available portion ends here

  //no_interrupts area-------
  // TIMEOUT CODE HERE. TO DETERMINE IF A RESISTANCE IS OPEN CIRCUITED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  if(interrupts_enabled && millis() - timestamp > measurement_timeout)
  {
    sensor_corruption[sensor_coord] = true; //label the resistance (indicated by sensor_coord) as true in the boolean array. this means it's open circuited (no signal from circuit)
    measurement_finished = true; ///we set this to true, so we can enter the next block of code
    ISR_unavailable = true; //small flag in order to not do calculations (some lines below) in case of an open circuit
  }
  //-------------------------

  if (measurement_finished)
  {

    if (!ISR_unavailable) //only make these calcs, if the ISR_unavailable is false. in other words if the ISR runs (so resistance is read)!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    {
        ticks = (overflows * 65536) + TCNT1;
        period = (ticks * 0.0625) / (number_of_samples - 1);

        //RESET THE SENSOR CORRUPTION TO FALSE HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!
        sensor_corruption[sensor_coord] = false;
        // if the res goes from open-circuited to working, this will restore the array so it's not labelled as open-circuited anymore
        // THE PROBLEM IS: THE FIRST MEASUREMENT AFTER IT GOES FROM OPEN -> CLOSED IS CORRUPTED. IT'S ALWAYS TO HIGH
        // MAYBE IT'S CAUSED BY THE FRICTION OF WIRES????
    }

      TIMER1_print_results();
      ISR_unavailable = false; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! reset ISR_unavailable for the next measurement
      if (full_mode)
      {
        sensor_coord++;
        select_sensor();
        //pulse_counter = 0;
        //TIMER1_clear();
        //interrupts_enabled = true; //necessary in full mode. useless if res is open-circuit, as this value never changed. but it doesn't hurt

        if (sensor_coord == NUM_OF_SENSORS)
        {

          sensor_coord = 0; //back from the beginning !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
          // full_mode = false; //no i want to continue having full mode
          // interrupts_enabled = false; //no, i want to continue having interrupts

          //after i measure all 8 resistances, the interrupt_enabled will be false. so code will be stuck in my no_interrupts area
          //this means the no_interrupts() area should run only when interrupts_enabled is true

          //remove the full mode line and reset sensor coord
        }

        /* We only enter the block of code we are now, when a measurement has happened (or when the no_interrupts
        area fired).
        We know that a measurement happened because the 'measurement_finished' variable is set by the interrupt
        (or set by the no_interrupts area, in order to enter the block we are now).
        But we ONLY want to enter the block we are now, when a measurement is finished, in order to process it.
        So now, that we did process it, in the end of this block, we have to reset the value.
        So we set measurement_finished to false, in order to not enter the block we are now, unless a new
        measurement has occured (or the no_interrupts area fired).
         */
        //measurement_finished = false;
        //timestamp = millis();  //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        //if i measure 1 resistance. here, interrupts_enabled will be false. this means no interupts.
        //this means my no_interrupts code will run. so it will always print. so no_interrupts area should run only whe interrupts_enabled is true
      }

      //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
       pulse_counter = 0;
       TIMER1_clear();
       interrupts_enabled = true;
       measurement_finished = false;
       timestamp = millis();  // refresh timer !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  }
 } //loop ends

/***** INTERRUPT ROUTINES *****/

void count_time_of_k_pulses()
{
  if (interrupts_enabled)
  {
    pulse_counter++;

    if (pulse_counter == 1)
      TIMER1_start();

    if (pulse_counter == number_of_samples)
    {
      TIMER1_stop();

      measurement_finished = true;
      interrupts_enabled = false;
    }
  }
}

ISR (TIMER1_OVF_vect)
{
  overflows++;
}

/***** FUNCTION FOR SENSOR SELECTION *****/

void select_sensor()
{
  digitalWrite(OE_BAR_PIN, HIGH);
  digitalWrite(S2_PIN, ((sensor_coord & 4) == 4) ? HIGH : LOW );
  digitalWrite(S1_PIN, ((sensor_coord & 2) == 2) ? HIGH : LOW );
  digitalWrite(S0_PIN, ((sensor_coord & 1) == 1) ? HIGH : LOW );
  digitalWrite(OE_BAR_PIN, LOW);
}

/***** TIMER1 FUNCTIONS (MODIFIED) *****/

void TIMER1_init()
{
  TCCR1A  = 0;
  TCCR1B  = 0;
  TIMSK1 |= (1 << TOIE1);
}

void TIMER1_start()
{
   TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
}

void TIMER1_stop()
{
  TCCR1B  = 0;
}

void TIMER1_clear()
{
  TCNT1     = 0;
  overflows = 0;
}

void TIMER1_print_results()
{
  Serial.println("----------------------------------------");
  Serial.print("SENSOR COORDINATE         = ");
  Serial.println(sensor_coord);

  //Added the if-else statement, to cover the possibility of open circuited resistance !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  if (sensor_corruption[sensor_coord])
  {
    Serial.println("This resistance is open circuited!!!");
  }
  else
  {
    Serial.print("NUMBER OF PULSES MEASURED = ");
    Serial.println(pulse_counter);

    Serial.print("TIMER1 VALUE              = ");
    Serial.println(TCNT1);

    Serial.print("TIMER1 OVERFLOWS          = ");
    Serial.println(overflows);

    Serial.print("TICKS                     = ");
    Serial.println(ticks);

    Serial.print("MEASURED PERIOD           = ");
    Serial.print(period);
    Serial.println(" US");

    Serial.print("MEASURED RESISTANCE       = ");
    double resistanse = ((period * GAIN_VALUE * 1000) / (4 * CAPACITOR_VALUE)) - R_BIAS_VALUE; //kΩ
    Serial.print(resistanse);
    Serial.println(" kΩ");

    Serial.println("----------------------------------------");
  }
}

You need to check serial inbetween of your infinite measurement loop. readString() is a bad choice for that, because it uses a 1s timeout. Please show us your full code or - if its too long - a minimal working example

I edited the question with the full code.

But the end of the loop, wont the execution always flow to the part where there is the Serial.available() check?

Maybe i should place the interrupts_enaled not at the end of the loop, but at the beginning? Because maybw now they are always enabled, so maybe my program doesnt have time to access the serial chekcing part.

why do you need to use interrupts?


text:
Problem connecting Arduino and ADC AD7606
Question is about using ADC AD7606 paired with Arduino (Arduino Mega).
I can’t reach the stated speed of this bundle, the question is also whether it is possible or not. ADC output mode is 16-bit parallel. The physical connection corresponds to that in the examples using Mitov's Visuino. The sensor that sends data to the ADC is AC102-1a, connected via the recommended power supply circuit.
Compiled program code (provided below) that outputs the result of receiving data from one ADC port to the serial port monitor (disabled during speed testing, so as not to slow down the speed of output to the port). Also it has the ability to estimate the speed of the program, as a number of passes of the loop cycle per second.
There were some ways to increase the speed of the Arduino, replacing the standard functions digitalRead, digitalWrite, etc.
The speed of the program, without taking into account the full connection with the ADC (when disabling the waiting BUSY) reaches 150,000+ iterations per second, but if we providing full communication with the ADC (according to the scheme found in the examples of programs with this ADC – the sequence of setting levels on pins READ, BUSY, RESET, etc.), the speed falls to 1700 iterations per second.
This speed is achieved when over-sampling is enabled. If you turn it off, the speed becomes 40000 iterations per second, while increasing the amount of noise in the received signal.
The question is, where is the error in the binding of the ADC command sequence, why is the speed so low, and whether it is possible to achieve an increase in the speed of work, ideally reaching the stated 200k operations per second for this ADC.

#define RESET_PIN 4
byte pin4mask = (1 << 5);
#define RESET_SET_OUTPUT      DDRG  |=  pin4mask // Pin 4 OUTPUT
#define RESET_SET_INPUT       DDRG  &= ~pin4mask // Pin 4 INPUT
#define RESET_WRITE_HIGH      PORTG |=  pin4mask // Pin 4 to HIGH
#define RESET_WRITE_LOW       PORTG &= ~pin4mask // Pin 4 to LOW

#define CHIP_SELECT_PIN 3
byte pin3mask = (1 << 5);
#define CHIP_SELECT_SET_OUTPUT      DDRE  |=  pin3mask // Pin 3 OUTPUT
#define CHIP_SELECT_SET_INPUT       DDRE  &= ~pin3mask // Pin 3 INPUT
#define CHIP_SELECT_WRITE_HIGH      PORTE |=  pin3mask // Pin 3 to HIGH
#define CHIP_SELECT_WRITE_LOW       PORTE &= ~pin3mask // Pin 3 to LOW

#define READ_PIN 2
byte pin2mask = (1 << 4);
#define READ_SET_OUTPUT      DDRE  |=  pin2mask // Pin 2 OUTPUT
#define READ_SET_INPUT       DDRE  &= ~pin2mask // Pin 2 INPUT
#define READ_WRITE_HIGH      PORTE |=  pin2mask // Pin 2 to HIGH
#define READ_WRITE_LOW       PORTE &= ~pin2mask // Pin 2 to LOW

#define START_PIN 6
byte pin6mask = (1 << 3);
#define START_SET_OUTPUT      DDRH  |=  pin6mask // Pin 6 OUTPUT
#define START_SET_INPUT       DDRH  &= ~pin6mask // Pin 6 INPUT
#define START_WRITE_HIGH      PORTH |=  pin6mask // Pin 6 to HIGH
#define START_WRITE_LOW       PORTH &= ~pin6mask // Pin 6 to LOW

#define BUSY_PIN 7
byte pin7mask = (1 << 4);
#define BUSY_SET_OUTPUT      DDRH  |=  pin7mask // Pin 7 OUTPUT
#define BUSY_SET_INPUT       DDRH  &= ~pin7mask // Pin 7 INPUT
#define BUSY_WRITE_HIGH      PORTH |=  pin7mask // Pin 7 to HIGH
#define BUSY_WRITE_LOW       PORTH &= ~pin7mask // Pin 7 to LOW
#define BUSY_READ            bitRead(PINH, 4)

//PIN 14
byte pin14mask = (1 << 1);
#define DB1_SET_INPUT       DDRJ  &= ~pin14mask // Pin D14 to INPUT
#define DB1_READ            bitRead(PINJ, 1)

//PIN 15
byte pin15mask = (1 << 0);
#define DB2_SET_INPUT       DDRJ  &= ~pin15mask // Pin D15 to INPUT
#define DB2_READ            bitRead(PINJ, 0)

//PIN 16
byte pin16mask = (1 << 1);
#define DB3_SET_INPUT       DDRH  &= ~pin16mask // Pin D16 to INPUT
#define DB3_READ            bitRead(PINH, 1)

//PIN 17
byte pin17mask = (1 << 0);
#define DB4_SET_INPUT       DDRH  &= ~pin17mask // Pin D17 to INPUT
#define DB4_READ            bitRead(PINH, 0)

//PIN 18
byte pin18mask = (1 << 3);
#define DB5_SET_INPUT       DDRD  &= ~pin18mask // Pin D18 to INPUT
#define DB5_READ            bitRead(PIND, 3)

//PIN 19
byte pin19mask = (1 << 2);
#define DB6_SET_INPUT       DDRD  &= ~pin19mask // Pin D19 to INPUT
#define DB6_READ            bitRead(PIND, 2)

//PIN 20
byte pin20mask = (1 << 1);
#define DB7_SET_INPUT       DDRD  &= ~pin20mask // Pin D20 to INPUT
#define DB7_READ            bitRead(PIND, 1)

//PIN 21
byte pin21mask = (1 << 0);
#define DB8_SET_INPUT       DDRD  &= ~pin21mask // Pin D21 to INPUT
#define DB8_READ            bitRead(PIND, 0)

//PIN 22
byte pin22mask = (1 << 0);
#define DB9_SET_INPUT       DDRA  &= ~pin22mask // Pin D22 to INPUT
#define DB9_READ            bitRead(PINA, 0)

//PIN 23
byte pin23mask = (1 << 1);
#define DB10_SET_INPUT       DDRA  &= ~pin23mask // Pin D23 to INPUT
#define DB10_READ            bitRead(PINA, 1)

//PIN 24
byte pin24mask = (1 << 2);
#define DB11_SET_INPUT       DDRA  &= ~pin24mask // Pin D24 to INPUT
#define DB11_READ            bitRead(PINA, 2)

//PIN 25
byte pin25mask = (1 << 3);
#define DB12_SET_INPUT       DDRA  &= ~pin25mask // Pin D25 to INPUT
#define DB12_READ            bitRead(PINA, 3)

//PIN 26
byte pin26mask = (1 << 4);
#define DB13_SET_INPUT       DDRA  &= ~pin26mask // Pin D26 to INPUT
#define DB13_READ            bitRead(PINA, 4)

//PIN 27
byte pin27mask = (1 << 5);
#define DB14_SET_INPUT       DDRA  &= ~pin27mask // Устанавливаем пин D27 в режим INPUT
#define DB14_READ            bitRead(PINA, 5)

//PIN 28
byte pin28mask = (1 << 6);
#define DB15_SET_INPUT       DDRA  &= ~pin28mask // Устанавливаем пин D28 в режим INPUT
#define DB15_READ            bitRead(PINA, 6)

//PIN 29
byte pin29mask = (1 << 7);
#define DB16_SET_INPUT       DDRA  &= ~pin29mask // Устанавливаем пин D29 в режим INPUT
#define DB16_READ            bitRead(PINA, 7)

#define OS2 10
#define OS1 9
#define OS0 8
#define RANGE_PIN 11

const long interval = 1000;

unsigned long previousMillis = 0;
unsigned long counter01 = 0;

void setup() {
  Serial.begin(9600);
  DB1_SET_INPUT;
  DB2_SET_INPUT;
  DB3_SET_INPUT;
  DB4_SET_INPUT;
  DB5_SET_INPUT;
  DB6_SET_INPUT;
  DB7_SET_INPUT;
  DB8_SET_INPUT;
  DB9_SET_INPUT;
  DB10_SET_INPUT;
  DB11_SET_INPUT;
  DB12_SET_INPUT;
  DB13_SET_INPUT;
  DB14_SET_INPUT;
  DB15_SET_INPUT;
  DB16_SET_INPUT;

  RESET_SET_OUTPUT;
  CHIP_SELECT_SET_OUTPUT;
  READ_SET_OUTPUT;
  START_SET_OUTPUT;
  pinMode (RANGE_PIN, OUTPUT);
  BUSY_SET_INPUT;

  RESET_WRITE_HIGH;
  delayMicroseconds(10);
  RESET_WRITE_LOW;

  CHIP_SELECT_WRITE_HIGH;
  READ_WRITE_HIGH;
  START_WRITE_HIGH;

  //Setting Oversampling Pins to Zero.
  digitalWrite(OS2, HIGH);
  digitalWrite(OS1, HIGH);
  digitalWrite(OS0, HIGH);

  digitalWrite(RANGE_PIN, HIGH);
}

void loop() {

  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    Serial.println( counter01 );
    counter01 = 0;
  }
  counter01 = counter01 + 1;

  /////////////////

  RESET_WRITE_HIGH;
  delayMicroseconds(1);
  RESET_WRITE_LOW;
  START_WRITE_LOW;
  START_WRITE_HIGH;

  while (BUSY_READ != LOW);
  CHIP_SELECT_WRITE_LOW;

  for (int AChannel = 0; AChannel < 1; ++AChannel)
  {
    READ_WRITE_LOW;
    uint16_t AResult = 0;
    if(DB1_READ == HIGH)
    { AResult |= ( 1 << 0 );}
    if(DB2_READ == HIGH)
    { AResult |= ( 1 << 1 );}
    if(DB3_READ == HIGH)
    { AResult |= ( 1 << 2 );}
    if(DB4_READ == HIGH)
    { AResult |= ( 1 << 3 );}
    if(DB5_READ == HIGH)
    { AResult |= ( 1 << 4 );}
    if(DB6_READ == HIGH)
    { AResult |= ( 1 << 5 );}
    if(DB7_READ == HIGH)
    { AResult |= ( 1 << 6 );}
    if(DB8_READ == HIGH)
    { AResult |= ( 1 << 7 );}
    if(DB9_READ == HIGH)
    { AResult |= ( 1 << 8 );}
    if(DB10_READ == HIGH)
    { AResult |= ( 1 << 9 );}
    if(DB11_READ == HIGH)
    { AResult |= ( 1 << 10 );}
    if(DB12_READ == HIGH)
    { AResult |= ( 1 << 11 );}
    if(DB13_READ == HIGH)
    { AResult |= ( 1 << 12 );}
    if(DB14_READ == HIGH)
    { AResult |= ( 1 << 13 );}
    if(DB15_READ == HIGH)
    { AResult |= ( 1 << 14 );}
    if(DB16_READ == HIGH)
    { AResult |= ( 1 << 15 );}

    READ_WRITE_HIGH;

    float AValue = float( int16_t( AResult ));
    if ( ! AChannel )
    {
      //Serial.println( AValue );
    }
  }
  CHIP_SELECT_WRITE_HIGH;
}

there is a typo in the #define READ_WRITE_LOW line ... in what universe is your English bad?  certainly not in this one ... upvote

why don't you use PORTA and PORTC for the 16 bit data bus? .... then read bytes, instead of single bits

Your English is fine. upvote.

To debug cases like this, use an oscilloscope and watch the pins. I'm sure you will find that it is your software, the bit-wise reading, not the ADC.

Thank you all for your answers!
@jsotola Can you specify what the typo is? As far as I can see, this entry is made by analogy with other lines. Is there a wrong port or something?
About byte reading. Oh, I see, maybe i'll try to resolder byte pins to PORTA and PORTC. It also will increase the speed but it seems like the main problem is in some other part.

@VE7JRO Thanks :)

@thebusybee Thank you, I hope I'll find the problem in code too, nowadays is rather complicated to reach to a friend with oscilloscope in this quarantine :)

the typo was corrected ... it was a missing comment delimiter


text:
How to calibrate Arduino DUE analog readings?
I am having a problem with the analog readings on my Due. On pin A4 and A5 I am measuring voltages:
double vcc = 3.288  // taken on pin 75 (ADVREF) ;
analogReadResolution(12);
result = analogRead(A4) * (vcc / 4095);   // result = 0.47+- 0.01      actual reading = 0.429
result = analogRead(A5) * (vcc / 4095);   // result = 0.49+- 0.01      actual reading = 0.555

As you may see I could not simply offset the value because both have very different offset: one is positive and the other is negative. The reading is off by 0.05v, which is inaccurate for a 12-bit ADC that offers 0.000805v resolution, almost a 1000x inaccuracy.
Is there any way to calibrate analogRead further without using additional external components on the pin?


text:
Calculating SpO2 using pulse sensor
I was wondering is there a way to calculate SpO2 using a pulse sensor?
I calculated BPM and stress before with pulse sensor and now I want to calculate SpO2.
Link to Pulse sensor manual

That depends on the pulse sensor. For measuring SpO2 you need a sensor with 2 different LED with different light wavelengths. What sensor do you use?

@chrisl well its a Biometric Pulse Rate or Heart Rate detecting sensor . check out the link : https://www.generationrobots.com/media/DetecteurDePoulsAmplifie/PulseSensorAmpedGettingStartedGuide.pdf

For measuring oxygen saturation (SpO2) with a pulse sensor, you need to use the fact, that hemoglobin, that carries oxygen, will reflect in different light wave lengths, as hemoglobin, which doesn't carry oxygen. But that also means, that you need to use light in at least 2 different wavelengths. Common are one red (about 660nm)(though green may also work) and infrared (about 940nm). When lighted sequentially with both LEDs, you can measure the refection of both parts and calculate the ratio between them (SpO2).
But your sensor only has 1 LED, which is green. So you cannot measure SpO2 with this sensor. You need one fitting the above description.


text:
char to String conversion in Arduino program
I have started learning about Arduino and am well versed in Java and Python. In an Arduino program, I need a character input via Serial to be stored in a String variable. From my previous programming experience, I knew that a code like the one below would give an error as char can't be converted into String like this.
void loop() {
  if(Serial.available()) {
     String s=(char)Serial.read();
  }
}

As expected, the above code gives an error on compiling. But when I first defined s and then assigned its value in a separate step in void loop(), I got no error.
void loop() {
  if(Serial.available()) {
     String s;
     s=(char)Serial.read();
  }
}

The above code yields no error despite the fact that it is almost similar to the first code. What I suspect is that it has something to do with String being a class. Can one tell what is going on?

this isn't an arduino specific error what you're trying to do is declare and initialize the variable in one statement which is causing the problem. As you've figured it out already. Declaring the variable first
String s;

and initializing it another statement does the job for you
s=blabla

Hope this helps. PS, try posting the error that you get during build process next time :)
EDIT:
 I think this needs more explanation. Basically why you cant declare and initialize at the same time in this case is because Serial.read is a synchronous request. Declaring an object requires acquiring the space for it, running any constructors and whatsoever, and doing while Serial.read() is an IO blocking operation. You could declare and initialize a String class variable given it was a string constant but not with anything like get_input or Serial.read
EDIT 2:
Further here's what I've found for you.
http://www.cplusplus.com/reference/string/string/string/
Apparently the  String class has a copy constructor which means when declaring the variable you initialize at the same time it uses the copy constructor, and which requires ADDRESS to a valid string(know that you can use a constant because C++ deals with all strings as the address to their first char). In your case the constructor raised an error because you pointed it to an undefined(Serial.read() ).
String mystring=Serial.read(); //error, uses copy constructor

However this would work
String mystring="hey juliet!" ; //uses the copy contructor which takes address to a char

Doing the same thing in two different lines works for the same reasons, it uses a different constructor
String mystring; //uses empty string constructor - okay so far
mystring=Serial.read(); // uses the overloaded = operator  --okay

You misunderstand Serial.read(): it does not return a String or sth. like a char array, but an integer, representing only the last byte in the input buffer that hasn't been read.
What you probably want to do is to interpret those incoming bytes as chars and accumulate those in a String.
E.g. like this:
String s="";
while(Serial.available()) {
  // as long as there are bytes in the buffer
  s+=(char)Serial.read(); // interpret int as char and append character to s
}

As using String can easily lead to crashes you should avoid dynamic memory allocation by using a fixed-size char arrays:
#define MAX_LEN 64
char s[MAX_LEN];
uint8_t i;
while (serial.available() && i<MAX_LEN) {
  s[i]=(char) Serial.read();
  i++;
}

Note: once you are that far you still have to handle, when you want the data to be ready to process (e.g. detecting a \n and setting a flag appropriately).

I don't misunderstand Serial.read(). I know it returns an integer and that's why I have put (char) in front of it. Nor, in my program, do I want a character sequence to be stored in a String s, just a single character and that's why Serial.read(). I was just testing and figured out something unknown and want to know a reason for that only.

I don't have much experience with Arduino's String type, however, most people (including myself) don't advise to use it. Because the Arduino only has 1 KB of SRAM and the String type has its own hidden memory allocation, you might run out of memory without you know it, resulting in crashing/frozen programs without a clue what is happening.
Instead use character arrays (like char str[10]) where you know exactly what is reserved.
However, to answer your question, what I expect since String is a class, there is a (copy) constructor in that class that takes a char and converts it into a String.

This will fix the problem:
void loop() {
  if(Serial.available()) {
     String s=(char*)Serial.read();
  }
}
This is because in C: Strings are defined as an array of characters.
You cannot assign a primitive to an array...
I guess the casting into pointer can be implicit as in your second example..


text:
ESP8266 EEPROM Reading extra character
I am very very new to ESP Programming.
I am trying to store Strings into EEPROM of ESP8266.
I am storing the string into eeprom successfully but while reading it from EEPROM extra character 'd' is coming into the picture. I assumed it is a character to end the string but it does being used into the String url and the further code of connecting to server is throwing error due to wrong URL.
My question is how to resolve this issue.
void writeString(int addr, String data)
{

   uint8_t size = data.length();
   for (uint8_t i = 0; i < size; i++) {
      EEPROM.write(addr + i, data.charAt(i));
   }
   EEPROM.write(addr + size, '\0');
   EEPROM.commit();

}

String read_String(int addr)
{

  String result = "";
  uint8_t count = 0;
  while (true) {
     char byte = EEPROM.read(addr + count);
     if (byte == '\0') {
       break;
     }
     else {
       result.concat(byte);
     }
  count++;
  }

 result = result.substring(0, (result.length()));
 return result;

}

Function Calling Snippet:
//Writting to EEPROM
String inputMessage1 = "myurl.co.in";
writeString(10, inputMessage1);

//READING from EEPROM
String hostStr = read_String(10);
Serial.print( "Connecting to Server... "+hostStr);

OUTPUT
Connecting to Server... myurl.co.ind

Include serial print into your routines and do a step by step debug on the serial monitor Its like finding Waldo.


text:
Arduino Nano use SPI pins as I/O pins? and still be able to do ISP?
I wonder if can use the Arduino Nano SPI-pins(MOSI,MISO & SCK) as I/O pins in a sketch? and still be able to program over ISP?
Of course I will physical disconnect the Arduino from any other hardware before programming.

why do you ask this?

Yes, you can use SPI in your sketch just as you like. The programming over ISP is triggered by resetting the microcontroller. That means, that when trying to program over ISP your sketch (which configures the SPI hardware for use) doesn't run. The programming is starting at a stage, before the sketch runs, thus the sketch cannot interfere.
By the way: The same is correct for programming over Serial, though for a different reason. Programming over Serial is done by the bootloader, which runs before your sketch.

So I can use them as digital I/O:s and I can also use the TX/RX as I/O:s but then I will be unable to use the COM-port to talk to the PC during operation, have I got it correctly?

Yes, you can use the SPI pins as IOs, as you like. For the hardware Serial pins TX and RX: You can configure them as IO, but you should consider cutting the traces to the USB Serial chip, that are connected to them. The lines of Serial (UART) are actively high. The USB Serial chip can interfere with the intended functions of the pins, when you don't cut the traces.

@chrisl - Usually that is not a problem. The USB serial interface connects to the processor via 1k resistors. When used as an output the processor can overdrive the resistor. When used as an input the driving source needs to be powerful enough to drive the 1k resistor as well as the processor.


text:
Whats wrong with my SPI code using uno?
I am stuck reading A1335 sensor through SPI. I have asked on the Aduino forum under the "Networking.." topic but no one is helping.
Link to other forum post
I have changed the code so many times now that I am completely confused. Noob at understanding the data sheet, my problem mite have something to do with timing. Noob at SPI , I think my arduino-SPI code is where I went wrong.
Almost certain my wiring is good.
latest code:
/* ******************************************************************************
 *  SPI read 3x A1335 rotation sensor chips with UNO and display on serial monitor
 *  Slave select pins 10 >ss1, 9 >ss2, 8 >ss3
 */
#include <SPI.h>

  // set slave pins and variables
  const int ss1 = 10;
  const int ss2 = 9;
  const int ss3 = 8;
  uint16_t Ang_ss1 = 0;
  uint16_t Ang_ss2 = 0;
  uint16_t Ang_ss3 = 0;

/*SPI settings here and not declared globaly for attaching different
  spi devices with difrent settings. Call transaction,begin with new
  settings*/

SPISettings settingsA(10000000,MSBFIRST,SPI_MODE3); //mode and 10mHz from manual, MSBfirst is a guess

void setup() {
   //set slave pins High and as outputs

  pinMode (ss1,OUTPUT);
  digitalWrite (ss1,HIGH);
  pinMode (ss2,OUTPUT);
  digitalWrite (ss2,HIGH);
  pinMode (ss3,OUTPUT);
  digitalWrite (ss3,HIGH);

  //set up register once and receive data in loop
  SPI.begin();
  Serial.begin(9600); //in different post it's said Serial.begin must be before SPI.begi......true or false
  SPI.beginTransaction(settingsA);
  digitalWrite (ss1,LOW);
  SPI.transfer(0x20);
  SPI.transfer(0);
  digitalWrite(ss1,HIGH);
  SPI.endTransaction();

}

void loop() {

SPI.beginTransaction(settingsA);

//select sensor 1 to 3 and read registers 0x20 and 0x21 after I get First 1 working

digitalWrite (ss1,LOW);      // sensor one read and store two bite data in ANG_ss1
//Ang_ss1 = SPI.transfer(0x20); //0x20 and 0x21 angle register
Ang_ss1 = SPI.transfer(0); // receive data 0x20 high byte
Ang_ss1 = <<8;
Ang_ss1 |= SPI.transfer(0);//receive low byte
digitalWrite(ss1,HIGH);

SPI.endTransaction();

//De-bug code: display values from sensors
Serial.print(Ang_ss1,BIN);              //Serial.print Ang_ss1 in binary
Serial.println(" ss1     ");
Ang_ss1 = <<4;  //firs 4 bytes are not part of angle
Ang_ss1 = >>4;
Serial.print(Ang_ss1);Serial.println(" ss1 shifted");

Serial.print(Ang_ss1 * 360/4096 );  // formula from programming manual for sensor removed brackets from '(360/4096)'
Serial.println(" DEG   ");

delay (1000);                       // to read serial monitor for debugging
}

The relevant data sheet and programming manual is linked in link up top. There's only 3 relevant pages in programming manual, page 21-23.
Also a video of output to serial monitor and garble I got on my oscilloscope.
Will only be back home tomorrow to test latest code on oscilloscope.
new Video of whats going on. New code uploaded but same problems.
Reminder data sheet and such in link at start of post.
Progress: seems uno 5V out not enough for three sensors. I am getting better results with just one. here is a video Still need help with code please
Confirmed can only run 1x SPI and when using I2C it becomes buggy with 2x sensors but one works a treat.
new Video
And code:
/* ******************************************************************************
 *  SPI read 3x A1335 rotation sensor chips with UNO and display on serial monitor
 *  Slave select pins 10 >ss1, 9 >ss2, 8 >ss3, UNO: SCL 13, Miso 12, mosi 11.
 *                                                  pink     yelo       orange
 **********************************************************************************/
#include <SPI.h>

  const int ss1 = 10; const int ss2 = 9; const int ss3 = 8;          //slave select pins
  uint16_t Ang_ss1 = 0;  uint16_t Ang_ss2 = 0; uint16_t Ang_ss3 = 0; //store 16bit register
  float Chip1; float Chip2; float Chip3;                             //after math valaue with commas( deg out of 360)

  SPISettings settingsA(10000000,MSBFIRST,SPI_MODE3);               //Spi settings

void setup() {

  pinMode (ss1,OUTPUT);                       //set slave pins High and as outputs
  digitalWrite (ss1,HIGH);
  pinMode (ss2,OUTPUT);
  digitalWrite (ss2,HIGH);
  pinMode (ss3,OUTPUT);
  digitalWrite (ss3,HIGH);

  Serial.begin(9600);
  SPI.begin();

}

void loop() {

SPI.beginTransaction(settingsA);

//select sensor 1 and read 0x20 and 0x21 registers

digitalWrite (ss1,LOW);                          // sensor one read and store two bite data in ANG_ss1
Ang_ss1 = SPI.transfer(0x20);                              //0x20 and 0x21 angle register
Ang_ss1 = Ang_ss1 <<8;
Ang_ss1 |= SPI.transfer(0);                               //receive low byte 0x21
digitalWrite(ss1,HIGH);

SPI.endTransaction();

Ang_ss1 = Ang_ss1 <<4;                                    //first 4 bytes are not part of angle
Ang_ss1 = Ang_ss1 >>4;
Chip1 = (float) Ang_ss1 / 16;                             // change binary to desimal
Chip1 = (float)Ang_ss1 /4096.0 * 360.0;                  //  formula in manual is n*(360/4096)

Serial.print(Chip1);
Serial.println(" DEG   ");

//delay (2000);                       // to read serial monitor for debugging

}

Lines like this Ang_ss1 <<8; do nothing. I guess you want to write the result back into the Ang_ss1 variable? Have you forgotten the equal sign?

Yes I forgot the equal sign. I will change that thank you, still not getting angle from sensor.

Please show the pure data, that you receive from the sensor (not some calculated value), so that we can see, if the SPI code itself works or not

chrisl, I am about to board a bus to airport. Hopefully I will have 'the latest code' tested and oscilloscope attached to see what code does by 13.00 today. Up to now just received one constant value through serial monitor

You may have to set the SPI pins to output yourself

Sim Son,  I have solved the problem. I had a power supply issue. The code now works but only for one sensor. I saw it was preferred to edit original Q? rather than comment down here. See last part of original post.  How do I mark this Q as solved or answered or what ever?


text:
No contact between DS18B20 and WeMos D1 Mini
I have a waterproof DS18B20 sensor that I have connected to a WeMos D1 Mini microcontroller. This controller connects to Wifi and an MQTT broker, sending the temperature from the sensor and goes to deep sleep.
Everything works nicely, except for the sensor reading. It returns -127, which means the sensor is disconnected. I have checked cables, measured voltage and everything should be just fine.
I have data cable for the sensor connected to D2, so in my sketch I have tried the following pins without success: oneWire(D2) - oneWire(2) - oneWire(GPIO4) - oneWire(4). No success.
Can anyone please help me with the following sketch?
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// WiFi settings
const char* ssid     = "[REDACTED]";
const char* password = "[REDACTED]";

// MQTT settings
const char* mqttServer   = "[REDACTED]";
const char* mqttUser     = "[REDACTED]";
const char* mqttPassword = "[REDACTED]";
const int   mqttPort     = 1883;
const char* mqttClient   = "[REDACTED]";
const char* mqttTopic    = "[REDACTED]";

#define durationSleep   15 // deep sleep length in minutes
#define NB_TRYWIFI      20 // number of wifi connection tries
#define ONE_WIRE_BUS     4 // temperature sensor connection

WiFiClient        espClient;
PubSubClient      client(espClient);
OneWire           oneWire(ONE_WIRE_BUS);
DallasTemperature sensor(&oneWire);

float celsius = 0;

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

  // Connect to sensors
  sensor.begin();

  // Setup WiFi
  WiFi.begin(ssid, password);
  int _try = 0;

  // Connect to WiFi
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    _try++;
    if (_try >= NB_TRYWIFI) {
      ESP.deepSleep(durationSleep * 1000000);
    }
  }

  // Setup MQTT
  client.setServer(mqttServer, mqttPort);

  // Get temperature in celsius
  sensor.setResolution(10);
  sensor.requestTemperatures();
  celsius = sensor.getTempCByIndex(0);

  // Connect to MQTT broker
  while (!client.connected()) {
    if (client.connect(mqttClient, mqttUser, mqttPassword)) {
      client.publish("mspa/temperature", String(celsius).c_str(), true);
      delay(1000);
    } else {
      delay(2000);
    }
  }

  // Go to sleep
  ESP.deepSleep((durationSleep * 60) * 1000000);
}

void loop() {
}

Did you add a pull-up resistor to the DS18B20 data pin?

//Call this function after sensor begin in setup.. share output
uint8_t findDevices(int DSPIN)
{
  OneWire ow(pin);

  uint8_t address[8];
  uint8_t count = 0;

  if (ow.search(address))
  {
    Serial.print("\nuint8_t pin");
    Serial.print(pin, DEC);
    Serial.println("[][8] = {");
    do {
      count++;
      Serial.println("  {");
      for (uint8_t i = 0; i < 8; i++)
      {
        Serial.print("0x");
        if (address[i] < 0x10) Serial.print("0");
        Serial.print(address[i], HEX);
        if (i < 7) Serial.print(", ");
      }
      Serial.println("  },");
    } while (ow.search(address));

    Serial.println("};");
    Serial.print("// nr devices found: ");
    Serial.println(count);
  }

  return count;
}

Thanks for your answer! Unfortunately this doesn't return anything: ets Jan  8 2013,rst cause:2, boot mode:(3,6)
load 0x4010f000, len 1392, room 16
tail 0
chksum 0xd0
csum 0xd0
v3d128e5c
~ld

Btw, I also tried multiple DS18B20 sensors, with no luck. Not sure what I am doing wrong. I also tested with other D1s, no luck.

Did you add a pull-up resistor to the DS18B20 data pin?

And for the stability (Read the comments) of your solution (Change anyway!) instead of
// IMPORTANT: This leads to crashes due to heap fracturing and imho does not work stable on micro controllers
 client.publish("mspa/temperature", String(celsius).c_str(), true);

 // Do this - define fixed chars before Setup - the compiler puts themto the stack
 char mqttBuffer[16] = '\0';
 char topic[] = "mspa/temperature";
 .....
 dtostrf(celsius,6,2,mqttBuffer); // convert a float to char
 client.publish(topic, mqttBuffer, true); // We use the fixed chars instead of heap fracturing Strings

Read more on evil Strings: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/
Hope this helps


text:
NodeMCU unable to connect to mobile hotspot when I include codes for reading the temperature sensor
Good day.
The NodeMCu successfully connected to mobile hotspot when i didn't put any others codes except the Wifibegin etc.
Howveer when I include some codes for temparature sensor, it keeps on connecting whereas the everything else including the SSID, password remain the same.
Below are my codes, I tried many, I mean I tried almost everything possible(that's stated in forums), read forums after forum. Please let me know if I missed something out here.
Thanks!
PS:  i attached my codes here
#include <ESP8266WiFi.h>
#include <WifiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

/* Wi-Fi setting connect to your smartphone Wi-Fi hotspot */
const char *ssid = "Thanks";
const char *password = "For reading";

/* Variable for taking out LM35 value */
String tempValue;
int analogValue;
int tempPin = A0;
float milliVolts;
float celcius;
/* Variable for sending data to server */
String postData;
int httpCode;
String payload;
void setup(){
//delay(1000);
Serial.begin(115200);
WiFi.begin(ssid,password);
Serial.println("");
Serial.println("Connecting");
/* If Wi-Fi hotspot is not found, show ..... in serial monitor */
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.println(".");
}
/* If Wi-Fi hotspot is found, show IP address in serial monitor */
Serial.println("");
Serial.println("Connected to ");
Serial.println(ssid);
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop(){
/* Getting value from LM35 */
delay(1000);
analogValue = analogRead(tempPin);
milliVolts = (analogValue/1024.0)*3300;
celcius = milliVolts/10;
tempValue = String(celcius);
Serial.println(tempValue);
/* Sending LM35 value to server */
HTTPClient http;
postData = "tempValue=" + tempValue;
http.begin("http://xxx.xxx.xx.xxx/dbInsert.php");
http.addHeader("Content-Type","application/x-www-form-urlencoded");
httpCode = http.POST(postData);
payload = http.getString();
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
http.end();
}

Your code is missing from the question. Also, what temperature sensor did you use and what pins did you use to connect your sensor?

@StarCat Hello. Thanks for replying..Edited. Codes as attached. 3.3V, GND,A0

Get rid of the delay - this STOPS processing for five seconds, not really what you want in a wifi scenario - some routers might disconnect you in this time if no pingbackis are comingIf you need a 5 second- non blocking break for your routines look at this example ArduinoIDE -> examples -> 2 Digital -> blinkwithoutdelay.
For further assistance copy and paste your code in code tags and not as a picture.

Hello . Thanks for your feedback. I  edited and pasted the code in text form. I tried omitting the delay(5000), but still doesn't work out... I reexamine the codes, and can't see the prob, please let me know you can detect the problem...thank you!!!

You still have delay in your loop, as long as you use delays debugging is useless /* Getting value from LM35 */
delay(1000); => get rid replace with something if(millis() - startTime < timeToWait)...  >> see blinkwithoutdelay example


text:
How to set a timer for a function and be able to reset it in the middle of the process?
Hello me and my friend have to do an assignment for school but we need some help. We have to make a LED turn on and of with a button and a relay. But when I press the button the LED should be on for 10 minutes and then go off unless we press the button inside those 10 minutes then the LED should turn off. Then repeat this process when we press the button again.
const int relay = 6;
const int button = 5;
int stateold = 1;
int statenew = 0;
int LED = 0;

void setup()
{
  pinMode(relay,OUTPUT);
  pinMode(button,INPUT);
  time = millis();
}

void loop()
{
  statenew = digitalRead(knop);
  if(stateold==0 && statenew==1){
    if(LED==0){
      digitalWrite(relay,HIGH);
      LED = 1;
      }
    }
    else{
       digitalWrite(relay,LOW);
        LED = 0;
    }
  }
 stateold=statenew;

}

you need to think about the LED on for 10 minutes differently ... it is not one 10 minute action ... it is two very brief actions 10 minutes apart ... do the assignment on paper ... use the kitchen light to represent the LED ... use a clock to time the 10 minutes .... write down everything that you have to do to turn on the light for 10 minutes ... pretend that the button was pressed at some point inside the 10 minute interval ... the steps that you wrote down can be turned into working code

Thank you, you helped me a lot to thing in the right direction.

happy to help .... programming is basically telling a very stupid machine exactly what to do at all times and how to react to every single event of interest

i forgot to mention, in the pencil and paper excersise in your kitchen, you cannot use your brain to remember anything ... things like starting time and the previous state of the button have to be remembered on paper

Below code is an example of what you described; pressing the button will turn on the LED and it will only turn off if 10 minutes passed or button is pressed again.
Read the comments in the code:
#define btn 5
#define rly 6

bool btnState;
bool ledState;
unsigned long timer = 0;

void setup() {
  pinMode(btn, INPUT_PULLUP);
  pinMode(rly, OUTPUT);
}

void loop() {
  btnState = digitalRead(btn); // Read the button status (default is 1)

  if (!btnState) { // If button state == 0 (pressed)
    ledState = !ledState; // Toggle this boolean
    timer = millis(); // and reset the timer
  }

  if (ledState) { // If LED state == 1
    digitalWrite(rly, HIGH); // Turn on the Relay
  } else { // Otherwise turn it off
    digitalWrite(rly, LOW);
  }

  if (ledState && millis() - timer > 600000) { // If 10 minutes passed turn off the relay
    digitalWrite(rly, LOW);
    ledState = !ledState;
  }
}

You should also de-bounce the button and you may want to turn on/off the LED when button is pressed and released, not just when it's pressed.

Thank you very much you help us a lot and it works now. Only in the last if statement you forgot a ledState = !ledState.

@daan YW, yep it should toggle the ledState in timer statement.


text:
Soil moisture sensor, weird readings
I'm  having a small problem with my soil moisture sensor
it gives me weird readings, in the second the smallest connection is made between the legs it just gives me 4096 (which is max possible value), its either about 0 or 4095
I can't really seem to see the problem, any help is appreciated
(the output voltage is read on an ESP32, almost visible in the bottom of the image)

And what is your soil monitor?

not sure what your question is, but I'm reading the output voltage on an ESP32

The output voltage of what? How is it wired? What is your schematic?

the output of the sensor, one leg has 3.3v going in, the other leg is wired to a GPIO pin

do you want the full schematic?

Yes please. Without that we're just stabbing in the dark.

how is the ground lead connected to the arduino?

its not an arduino, its an ESP32, but through the pcb

now I've added the full schematic

Is the soil probe component just two metal prongs?

yes, just 2 metals "prongs"

It looks like you're trying to measure the resistance of soil by connecting an ADC input through the soil to VCC.  That is not the way to to it.
At the moment you effectively have this schematic for that portion:

simulate this circuit – Schematic created using CircuitLab
The voltage dropped across the soil is proportional to the current flowing through it. And there is no current flowing through it1 because there's no path to ground, only the very high impedance of the ADC.
So you never see anything except VCC (or a floating input when the probe is not in the ground).
To measure a resistance like that you have to have it as one half of a potential divider, just like you would for an LDR.

simulate this circuit
What actual value R2 should have depends entirely on the resistance range detected by your probe. It can be good to experiment with different values until you find one that works for you.

1: Actually there is some small leakage current through the ADC to ground, but that is so tiny we can ignore it.


text:
I have a question,an error occured in my code saying TIMSK was not declared in the scope(There are no errors)
#include <SmartInventor.h>

void setup() {
  SmartInventor.DCMotorUse();

}
void loop() {
  // M1, M2, M3
  // CW, CCW, STOP
  // 0-100
  // 0-360

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(5000);

  SmartInventor.DCMotor(M1, CCW, 10);  //Music starts  //0:00:06
  delay(2000);

  SmartInventor.DCMotor(M1, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(11000);

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0); //Music stops   //0:00:32
  delay(10000);

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(5000);

  SmartInventor.DCMotor(M1, CCW, 10);
  delay(1000);

  SmartInventor.DCMotor(M1, CW, 10); //Music starts back up    //0:00:44
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(18000);

  SmartInventor.DCMotor(M1, CCW, 10);
  delay(3000);

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 10);
  delay(8000);

  SmartInventor.DCMotor(M1, CW, 10); //Music stops   //0:01:15
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(5000);

  SmartInventor.DCMotor(M1, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(3000);

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0); //Music starts up agian   //0:01:31
  delay(11000);

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0); //Music stops     //0:02:03
  delay(23000);

  SmartInventor.DCMotor(M1, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0); //Music starts up agian   //0:02:14
  delay(12000);

  SmartInventor.DCMotor(M1, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(6000);

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(6000);

  SmartInventor.DCMotor(M1, CCW, 10); //Music Ends    //0:02:40
  delay(2000);

  SmartInventor.DCMotor(M1, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M1, STOP, 0);
  delay(3000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(5000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000)

  ;SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(13000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(13000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(13000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000)

  ;SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CCW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(2000);

  SmartInventor.DCMotor(M2, CW, 10);
  delay(2000);

  SmartInventor.DCMotor(M2, STOP, 0);
  delay(7000);

}

A different user asked the same question a few days ago. Are you this user? As written in the comments for these questions, you should always include the full error message into the question. "There are no errors" is just wrong, simce you mention the error right before that

For which board are you compiling the code? And provide a link to the smartinventory library

The SmartInventor library is only for the Rokit Smart board. Why are you trying to use it with an Arduino Mega?

The SmartInventor library is to be used with the Rokit Smart board. That board is based around the ATMega32.
The Arduino Mega is not a Rokit Smart board, so the library will not work, since the Arduino Mega us based around the ATMega2560. The two chips are different, and have different sets of internal peripherals. So the registers have different names accordingly.

Ok so what board can I use for Rokit smart

The Rokit Smart.

Im just gonna write a new code for the mega2560 Arduino board. Can you guys tell me how to write the same code that I did with Rokit smart but in  the Arduino language

That all depends what it is you are trying to do, and what you are trying to do it to.

can I code of this typehttps://www.bing.com/videos/search?q=coding+two+dc+motors&&view=detail&mid=A6D70717250191472167A6D70717250191472167&&FORM=VRDGAR&ru=%2Fvideos%2Fsearch%3Fq%3Dcoding%2520two%2520dc%2520motors%26qs%3Dn%26form%3DQBVR%26sp%3D-1%26pq%3Dcoding%2520two%2520dc%2520motors%26sc%3D0-20%26sk%3D%26cvid%3D6A02585DECEB4033ADC28846E118035B for the mega board

Probably. Again: what are you trying to control? The Mega is just the brain. You must have something connected to it.

3 DC motors. But is 1 and 3 the same thing like Rokit smart? If it is than ill code 2 motors on one board and the other motor on another board.

No clue. How are you connecting the motors? You must have since kind of motor shield. I suggest you start by looking at the examples given by the manufacturer of that shield.

Yah I do have a motor shield


text:
Division with big constant number. Ideas to make it more efficient?
Im reading the voltage applied to my microcontroller using the internal voltage reference.
Here the topic is talked, and there are some working examples.
Im NOT using this examples, im using my own library to do this.
In short, works like this:

Microcontroller has fixed internal voltaje reference of 2.048v that can be read
Reading this value with the ADC will give a value from 0-255 (im using 8 bit ADC for efficiency)
Depending on the value read, you can calculate the voltage at the Vcc pin
Math is like this:

Vcc_voltage = ADC_MAX_VALUE * VREF_VOLTAGE / adc_value
Where:

Vcc_voltage: Voltage calculated at the VCC input of the microcontroller
ADC_MAX_VALUE: the maximum value that the ADC could give (CONSTANT: 255 in this case)
VREF_VOLTAGE: voltage of the internal fixed reference (CONSTANT: 2.048v in this case)
adc_value: value read by the ADC at the internal voltage reference (VARIABLE: from 0 to 255)

So the calculation result:
Vcc_voltage = 255 * 2.048 / adc_value
In order not to use floats, I multiply the VREF_VOLTAGE * 1000. New calculation:
Vcc_voltage = 255 * 2048 / adc_value
Or:
Vcc_voltage = 522240 / adc_value
And this is where im stuck. Im running out of flash, and im optimizing every part of the code. At the moment this is a "int32" division with a int16 result".
I think this could be reduced by some "binary trick", some wise programmer advice or approaching the formula from a different point of view.
Any suggestion?

I think the wisest programmer advice would be not to try to optimize this code if it's regarding FLASH (not even SRAM). You might save 1 or a few bytes. I'm sure there are other parts in your code where the gain is bigger, and if not, than this will not help much either. Readability/maintainability is also important which will normally suffer a lot if you are into these kind of optimalizations.


text:
Boolean variable with if statement
I am trying to use boolean variables with two if statements. The second if condition never evaluates to be true. May be it's a problem with how I have defined my boolean variables. Do you see the mistake?
Here is the code:
int x = 0;
boolean state1 = (x <= 10);
boolean state2 = (x > 10);

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

void loop() {

  x++;

  if (state1) {
    Serial.println("x <= 10");
  } else if (state2) {
    Serial.println(" x > 10");
  }

}

You never update your state variables. When you assign in C you assign the result of the formula, not the formula itself.

I was trying to assign the two conditions to the boolean variables so yes like you said I was assigning the formula.

This question does not concern the Arduino but is a general programming question.

I asked this question to be moved to Stackoverflow as it is not Arduino related.
However to answer your question, you assign the booleans before you start the program, so they are never re-evaluated and always keep their initial value, based on when x = 0.
What you should do is, reevaluate them within the loop:
int x = 0;
boolean state1;
boolean state2;

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

void loop() {
  x++;
  state1 = (x <= 10);
  state2 = (x > 10);
  if (state1) {
    Serial.println("x <= 10");
  } else if (state2) {
    Serial.println(" x > 10");
  }
}

Also, because if state1 is true, state2 will always be false and vice versa, so you don't need to have two booleans. This will give:
int x = 0;
boolean state;

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

void loop() {
  x++;
  state = (x <= 10);
  if (state) {
    Serial.println("x <= 10");
  } else {
    Serial.println(" x > 10");
  }
}

Beyond that, you don't need to define the boolean globally, because you only need it inside the loop and is not need to be 'stored' from one loop to another. So you get
int x = 0;

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

void loop() {
  x++;
  boolean state = (x <= 10);
  if (state) {
    Serial.println("x <= 10");
  } else {
    Serial.println(" x > 10");
  }
}

Of course you can also directly check for x <= 10 instead of storing it in a boolean, but I assume you need the boolean elsewhere further within the loop function later.

Yes I see the issue now. I saw a few sketches where boolean variables were used in if statement and thought that I could use them to store the conditions itself. I was assuming that since the condition is now stored / assigned to the boolean variable so every time the variable is used it will automatically compare the condition to the current value of x. But your code helped me see the need to update the variables and storing them locally. I understand it better now. Thanks

You are welcome ... True, there is a difference between declaring the variables (boolean b), and assigning (b = x). When x changes, b does not change, until you perform a new assignment (unless it is a pointer). I suggest to read about C/C++, it makes using the Arduino much more powerful).

Yes I do plan to learn more C/C++ but at this stage just getting familiar with basic electronics and writing simple arduino sketches. So the next step is definitely digging deeper into C.

You cannot do anything at the same time (I'm also still learning electronics)


text:
CIPSEND to ESP8266 returning bytes but no content
I am trying to send a GET request from an Arduino Uno connected to an ESP8266 through SoftwareSerial. I can't get it working directly in the code so I've stripped it down to a script that passes serial monitor queries like so:
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial esp8266 (rxPin, txPin);

void setup()
{
  Serial.begin(115200);
  esp8266.begin(115200);
  delay(1000);
}

void loop()
{
  if (esp8266.available()) Serial.write(esp8266.read());
  if (Serial.available()) esp8266.write(Serial.read());
}

I setup and connect the ESP8266 to my router like so from the serial monitor:
AT+RST
AT+CWMODE=3
AT+CWJAP="rwifi name","wifi password"
AT+CIFSR
AT+CIPMUX=0
AT+CIPSTART="TCP","www.abcdefg.com",80
AT+CIPSEND=61
GET /in-progress/ab/i.php?c=20 HTTP/1.0 Host: www.abcdefg.com

Everything works fine up until the CIPSEND, the GET request part, and the serial monitor output the following:
AT+CIPSEND=61

OK
> i.php?c=20 HTTP/1.0

busy s...
Recv 61 bytes
SEND OK

I know there is a 64 byte limit for the serial monitor. my GET is 61 bytes. I'm getting bytes back but not the content from the page (it should be the word "yes") and not even a content from a 404 page. Web side my php page is a counter that adds 1 to a number in a txt file - it doesn't increment (it does work if I call it from the web browser).
Where I am going wrong here with my CIPSEND? It looks like it is correctly formed to me.
-----edit-----
Based on comments below this is the latest GET request I have tried:
AT+CIPSEND=73
GET /i.php HTTP/1.1\r\nHost: www.abcdefg.com\r\nConnection: close\r\n\r\n

I have shortened my pathway to the php file as much as possible, added the carriage returns and newlines between request and each header, added the double carriage return and newline at the end. The request now returns +IPD,919:HTTP/1.1 400 Bad Request. This error 400 is not logged on my website.

GET /in-progress/ab/i.php?c=20 HTTP/1.0 Host: www.abcdefg.com is not a valid GER request. Headers go on separate lines separated by \r\n.

You need to terminate the GET request with proper \r\n, and the http header as well. So it should be GET /in-progress/ab/i.php?c=20 HTTP/1.0\r\nHost: www.abcdefg.com\r\nConnection: close\r\n\r\n. I have an example on my github you might want to take a look.

@garrettlynch, upvote for presenting the correct way of debugging connectivity issue between the arduino and the ESP8266

@hcheung thanks, I've tried it with carriage returns and new lines as instructed. I'm getting +IPD,919:HTTP/1.0 400 Bad Request - I wonder if this is something to do with the AT+CIPSEND=bytecount I'm sending. I'm unclear as to what the count is of. The documentation states it's the "length of the data that will be sent". Does that mean just the pathway sent (i.e. /in-progress/ab/i.php?c=20) or does it include everything else in the line GET /in-progress/ab/i.php?c=20 HTTP/1.0\r\n? I've dug through your libraries code and as far as I can tell you are counting the whole line.

yes, I was sending line by line with multiple AT+CIPSEND commands, the length is included \r\n. Your ESP8266 received 400 Bad Request might be other issues. Do you check your server/php log to see what exactly received and why it is a bad request?

BTW, the last http header should have double \r\n\r\n, which is typically the header for Connection: close\r\n\r\n. Also, make sure you send the correct "Host: hostname\r\n" header, I remember I've see 400 before causing by incorrect host name or missing the http header.

@hcheung the Host: hostname\r\n header seems to be specific to HTTP 1.1 from what I've read. I've tried with HTTP 1.0 as well without hostname and I get the same error 400 so I think I can rule that out as the issue. Yes my last header is using a double \r\n\r\n. I've checked my sites access logs and error logs and there is no trace of any error 400 or requests to that page i.php other than the three I did from a browser today to check it was working.

you can't send a two or more line http request from Serial Monitor. it is not possible. the \r\n are not converted to line ends. they are sent as \ and r and \ and n

Yeah, like someone already said, you can't send CRLF by typing them into the Serial Monitor. Let the serial monitor itself append that for you instead. You have to set the Line Ending at the bottom to "Both NL & CR" and then send your HTTP headers, one line at a time. For each \r\n in your request, you press Enter, type the next line and so on, until the request is complete.

In my experience, the "busy" message appears when you try to start a new AT command or to send data before the ESP8266 is ready. You say that you are running this test with the commands in "a script" which suggests to me that there is no significant delay between lines.
You should either wait between commands until the EXP8266 responds (usually with "OK" or ">") or add a delay of a few seconds between commands.

No I said "I've stripped it [my code] down to a script that passes serial monitor queries" - the AT commands are coming from the serial monitor and the prior commands have completed before the GET request is sent. I have moved beyond this, however, and am getting Bad Request responses now. Please see the edit to my question.


text:
AVR & PIC 8-bit Microcontrollers - Can you add: external flash memory, external RAM, video & audio output, more address busses?
so I was planning on creating a mini PC out of basic ICs and 8-bit microcontrollers such as ATTinys and/or PICs and I have several questions regarding those:

Can you add external RAM, say with SRAM, DRAM chips, so the microcontroller can handle larger programs? (ones requiring more memory to be executed). I've seen an excellent discussion here: External Flash Memory for ATtiny85, which exclaims that I can't do that with AVRs (but why exactly is that? What about PICs, or any 8-bit uCs for that matter).
Can you add external memory, like flash or EEPROM, so that the microcontroller can store some files (sort of a hard drive (but more like an SSD I guess).
Also, how would you go around connecting memory chips together to get more memory out of them? Would there be a difference with memory chips like serial flash and parallel flash?
Can you use them to output and create basic audio & output HDMI? (or communicate with external ICs to do that task)
Can you somehow connect say 2 8-bit ATTinys to get a pseudo 16-bit microcontroller? Would that mean they could process more data at the same time?

Thanks,
some guy on the internet.

Why do you want to do that, simply for the sake of it?  There are several extremely low-cost 64-bit computers around incl Raspberry Pi.  P.S. the question is not about Arduino, voting off topic.

You’re much better off with a general purpose microprocessor or a single board computer. AVRs and PIC are great and versatile devices but simply not the best suitable for what you describe.

I know what you're getting at, I would be better off with anything else, but I just wanted to use these uCs as a proof of concept that they can be converted into a "usable computer".

I’m voting to close this question because it should be migrated to electronics.stackexchange.com

Dmitry Grinberg built an ARM emulator on an AVR microcontroller, then booted Linux on the emulated ARM. Emulation lifts some of the limitations of the microcontroller, like the inability to execute instructions from RAM.

Yes, you can connect external RAM chips through the typical interfaces (mainly SPI or I2C). But you cannot execute code from it. The microcontroller is an IC, meaning Integrated Circuit. It is hard wired internally to execute from internal flash. You cannot change that. That is valid for most microcontrollers, that executes from internal flash (which is somewhat a definition of a microcontroller). A processor - in contrast- like in a computer, is build to execute code from elsewhere. Note: Some microcontrollers have the ability to execute from external flash. The ESP boards are a good example for this, because they already use an external flash chip, which is soldered onto the board. You can extent the available flash over the SPI flash pins (the SPI bus, where the flash is connected); though this is not really a topic for beginners. You might wanna look into that.
If your code, that you want to store externally, isn't that complex, you could save the code there as an own (most likely binary) data format and write code for the microcontroller, that takes that data and executes corresponding functions. So basically an interpreter. Though on the small microcontrollers only code for rather small functionality will fit.

Yes, you can add external storage. Which storage depends on many factors. You can by external flash or EEPROM chips, just like external RAM chips. Common storage devices for microcontrollers are SD cards, because they can easily interfaces via SPI. You can even have a file system there (though the size is somewhat limited by the available RAM of your microcontroller, because it needs to load the file table). Maybe you can even connect an SSD, but you will have to look, if you can set up the corresponding interface for it. A microcontroller does not have SATA interfaces or similar. And adding extra chips for these leaves you fastly with interfacing chips, that are way more capable as the main chip itself (see Wifi and the ESPs: You could add Wifi to an Arduino Uno project with it, but the ESP is way more capable, than the Uno). Then you would need to ask yourself: Is this really a good idea?

I think most memory chips (whichever kind) are not daisy chainable. Mostly they use a Single-Master-Multiple-Slaves interface like SPI. You could connect multiple memory chips to the SPI bus and communicate sequentially with them. The difference between parallel and serial flash chips is their communication interface. Serial can be something like SPI. Parallel communication will send multiple bits at once over the corresponding amount of wires (mostly 8, means 1 byte). Here you need the corresponding number of free pins on your microcontroller. Though parallel interfacing is often not advisable. Especially the small microcontrollers are too slow, to profit from the faster interface. And instead of using at least 9 pins, you could also use 3 for SPI and get the same transmission speed in the end.

Yes, they can. Though it really depends on the used microcontroller and the project topology. When using something like the DFmini player, any microcontroller can play audio (from files on a micro SD card in the player). When the microcontroller should play sounds itself, you can get very different results, depending on the chip capabilities. An ESP32 for example has a dedicated I2S interface, which is build for transmitting sound to an output device.
About video: AVR based microcontrollers (or similar PICs) cannot really handle video. For example: The most, that you can get out of an Arduino Uno (Atmega328p) is a very very limited VGA signal (very small resolution, only a few colors). HDMI is out of range for any of them. Surely you would want to draw on the screen, that is connected to the HDMI interface, to build up a visual interface. I think, that is just not possible with such small microcontrollers. They are not meant for this. Though you might find some very specialized chip, that you could use in such a way. If, that chip would be way more expensive as buying multiple Raspberry Pis. But if you are willig to compromise you may find a smaller sized display (like a few inches) with a connected controller, that you can control via the Arduino. But still you will have very low refresh rate, so no moving images, more like still images.

No, just as 2 32-bit computers do not make 1 64-bit computer. That is just not, how everything works. Each microcontroller can still only process 8 bit at a time out of it's own memory. Depending on the task, you may try to give them different tasks. That would give you more computation power in theory, but it's not the same as a 16-bit controller.

I assume, that you are doing this for fun or for the grind, so I will not say, that you should buy a Raspberry Pi. Though I think, you might look into the wrong way. You cannot make a truck out of parts for a mini, though many of the components work in a similar way. To get all the difficult functionality (audio, video, big storage, ...) out of your self build computer, you need to use computer parts, not microcontroller parts.
If you are happy with much less capabilities, many people in the past have build their own computers out of more basic parts as microcontrollers (down to the big range of logic gates). Microcontrollers live in the world between computers and basic logic components. They are too integrated for extending their capabilities much.

Yes you can, and even execute code from it on PIC18 and PIC17 microcontrollers up to 2MB if external program memory can be added but most variants lac the external program memory interface.
For example the pic18f8x8x you can even implement a memory bank system to address much more than 2MB like PCs did in the early times of the x86 called XMEM extended memory.


text:
Receiving multiple Values from android via Bluetooth
my question is, how can I receive 3 integer values in Arduino, which I send from my android phone. I send all 3 values at the same time and I also need to read them in about the same time.
I hope you can help me.

If there are no other constraints, send them as a text with delimiters and a  terminating character.
e.g. something like "123;45;678\n"
On the arduino, either manually check for those delimiters and convert the digits to a number on the fly, or use strtok  and atoi after reading the whole line.


text:
Using PortB as a sink, not working
Out of ideas here, i try using PB0-3 as sinks for a LED matrix and the pins just won't sink.
My test code:
void setup() {
  //bitClear(SPCR, 6);
  pinMode(PD5, OUTPUT);

  pinMode(PB0, OUTPUT);
  pinMode(PB1, OUTPUT);
  pinMode(PB2, OUTPUT);
  pinMode(PB3, OUTPUT);

  digitalWrite(PB0, LOW);
  digitalWrite(PB1, LOW);
  digitalWrite(PB2, LOW);
  digitalWrite(PB3, LOW);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(PD5, HIGH);
  delay(1000);
  digitalWrite(PD5, LOW);
  delay(1000);
}

(Using bog standard Blink as a starting point for tests)
My controller is an ATMega328P programmed using USBaspLoader on my own PCB.
If i connect the physical pin that should be sinking with a piece of wire to ground the LED starts blinking, so the "sending" part seems to work but the "receiving" part doesn't.
As you can see i tried manually disabling the SPI port, no luck either.
I tried different controllers, among them a good old ATMega8-16, nothing seems to work.
I even breadboarded a test circuit but no luck, PortB wont sink.

Why are you using the likes of PB3 with digitalWrite() etc?

PB3 etc don't refer to Arduino pins. Instead they refer to the bits in the internal registers.
To use digitalWrite() etc you must use Arduino pins not internal register bit numbers.
The pin to port/bit mapping is defined by what board you have selected, and if you want to look it up you should examine the pins_arduino.h file for your selected board.

Thanks, i thought, because the compiler wasn't complaining, that they where defined as such. Is there some way to look at the intermediate code?

You mean the assembly code? You can disassemble the elf file with avr-objdump -S I guess, but that's probably not of any help to you.  In general PBx is defined as x (PB3 is defined as 3) and is intended to be used as PORTB |= (1 << PB3).


text:
Arduino HTTP Command - ESPEasy
I am new to Arduino and although I am starting with and creating some basic projects my end goal right now is to be able to turn my Sonoff on and off via a momentary switch attached to my Wifi enabled Arduino board (Particle Photon). I'm not looking for the code I would just like to pointed in the right direction.
I flashed my Sonoff so that it now runs ESPEasy and set it up so that I can control it from my browser using http://10.0.1.35/control?cmd=event,TurnOn to turn it on and http://10.0.1.35/control?cmd=event,TurnOff to turn it off. I have been reading about using POST or GET requests but none of the examples I find seem to send a similar command to how I currently have my Sonoff set up.
My question is what should I be looking at and reading about to be able to send these types of commands via the Arduino?
Any recommendations are greatly appreciated. I'm thoroughly enjoying getting into coding but finding this step quite challenging to say the least!
Thanks!

Particle Photon is not Arduino. with Arduino you would use a WiFi library for your WiFi adapter. the Arduino WiFi libraries have examples

My apologies, I suppose it isn't, but I'm working on the basis that the solution will be the same between Arduino and the Photon board I'm using.

https://www.arduino.cc/en/Tutorial/WiFiWebClient

Have you tried to perform a HTTP Get request with exactly the URLs, that you already used in your browser? The browser also simply does a Get request

Thanks for the heads up that the GET request was indeed the right way to go. I managed to work through this a bit today got the GET request to work. I also hooked up the button and got that to send the two requests on both press and release. I know this code is for the Photon but I hope it'll help someone else out
// TCPClient
#define LIB_DOMAIN "10.0.1.252"
TCPClient client;

// This constant won't change:
const int  buttonPin = D1;    // the pin that the pushbutton is attached to
const int ledPin = D7;       // internal LED pin

// Variables will change:
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
  pinMode(ledPin, OUTPUT); // Initialize D7 pin as output
  pinMode(buttonPin, INPUT_PULLUP);
  // Initialize D1 pin as input with an internal pull-up resistor
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, turn on or off
    if (buttonState == HIGH) {
        digitalWrite(ledPin, LOW);
        //TCPClient
        client.connect(LIB_DOMAIN, 80);
        client.println("GET /control?cmd=event,TurnOff HTTP/1.0");
        client.println("Host:" LIB_DOMAIN);
        client.println("Content-Length: 0");
        client.println();
    } else {
        digitalWrite(ledPin, HIGH);
        //TCPClient
        client.connect(LIB_DOMAIN, 80);
        client.println("GET /control?cmd=event,TurnOn HTTP/1.0");
        client.println("Host:" LIB_DOMAIN);
        client.println("Content-Length: 0");
        client.println();
    }
    // Delay a little bit to avoid bouncing
    delay(50);
  }
  // save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;

}


text:
Can't get keypad to use Keyboard.write on an Arduino Uno
I've tried to use Keypad.h and Keyboard.h libraries to get my Arduino to use my Keypad for Keyboard input.
I'll start with working keypad code (which is pretty easy but it's my first post so I want to make it as neat as possible).
Working keypad
#include <Keypad.h>

const byte Rows = 4;
const byte Cols = 4;

char hexaKeys[Rows][Cols] = {
  {'1', '2', '3', 'A' },
  {'4', '5', '6', 'B' },
  {'7', '8', '9', 'C' },
  {'*', '0', '#', 'D' },
};

byte rowPins[Rows] = {9,8,7,6};
byte colPins[Cols] = {5,4,3,2};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins
, Rows, Cols);

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

void loop() {
char customKey = customKeypad.getKey();
  if (customKey){
    Serial.println(customKey);
  }
}

At this point, using Serial Monitor, I can see that all keys are being read and printed out no problem.
Then, I tried adding the Keyboard.h library to get it to act as an keyboard input
Not Working Keyboard Input
#include <Keypad.h>
//#include <Keyboard.h>
const byte Rows = 4;
const byte Cols = 4;

char hexaKeys[Rows][Cols] = {
  {'1', '2', '3', 'A' },
  {'4', '5', '6', 'B' },
  {'7', '8', '9', 'C' },
  {'*', '0', '#', 'D' },
};

byte rowPins[Rows] = {9,8,7,6};
byte colPins[Cols] = {5,4,3,2};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins
, Rows, Cols);

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

void loop() {
char customKey = customKeypad.getKey();
  if (customKey){
    Serial.write(customKey);
    //Keyboard.write(customKey);
  }
}

The commented out sections are where I've added changes.
The problems I've encountered:
 - Can't include Keyboard.h on regular Arduino Uno. I've read that changing board type to Arduino Leonardo helps, and it does, but then the Serial Monitor is greyed out and doesn't read keypad input.
 Using following code I get following error message ( I'm still 'using' Leonardo board since Keyboard.h doesn't want to work with Uno)
#include <Keypad.h>
#include <Keyboard.h>
const byte Rows = 4;
const byte Cols = 4;

char hexaKeys[Rows][Cols] = {
  {'1', '2', '3', 'A' },
  {'4', '5', '6', 'B' },
  {'7', '8', '9', 'C' },
  {'*', '0', '#', 'D' },
};

byte rowPins[Rows] = {9,8,7,6};
byte colPins[Cols] = {5,4,3,2};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins
, Rows, Cols);

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

void loop() {
char customKey = customKeypad.getKey();
  if (customKey){
    Keyboard.write(customKey);
  }
}

processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:152)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:77)
    at processing.app.SketchController.upload(SketchController.java:732)
    at processing.app.SketchController.exportApplet(SketchController.java:703)
    at processing.app.Editor$UploadHandler.run(Editor.java:2047)
    at java.lang.Thread.run(Thread.java:748)
Caused by: processing.app.SerialException: Error touching serial port 'COM7'.
    at processing.app.Serial.touchForCDCReset(Serial.java:107)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:136)
    ... 5 more
Caused by: jssc.SerialPortException: Port name - COM7; Method name - openPort(); Exception type - Port busy.
    at jssc.SerialPort.openPort(SerialPort.java:164)
    at processing.app.Serial.touchForCDCReset(Serial.java:101)
    ... 6 more
An error occurred while uploading the sketch
Exception in thread "Thread-28" java.util.ConcurrentModificationException
    at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:966)
    at java.util.LinkedList$ListItr.next(LinkedList.java:888)
    at processing.app.packages.LibraryList.getByName(LibraryList.java:61)
    at cc.arduino.contributions.libraries.LibrariesIndexer.addToInstalledLibraries(LibrariesIndexer.java:130)
    at cc.arduino.contributions.libraries.LibrariesIndexer.scanLibrary(LibrariesIndexer.java:229)
    at cc.arduino.contributions.libraries.LibrariesIndexer.scanInstalledLibraries(LibrariesIndexer.java:201)
    at cc.arduino.contributions.libraries.LibrariesIndexer.rescanLibraries(LibrariesIndexer.java:161)
    at cc.arduino.contributions.libraries.LibrariesIndexer.setLibrariesFolders(LibrariesIndexer.java:120)
    at processing.app.BaseNoGui.onBoardOrPortChange(BaseNoGui.java:677)
    at processing.app.Base.onBoardOrPortChange(Base.java:1336)
    at processing.app.Editor$UploadHandler.run(Editor.java:2083)
    at java.lang.Thread.run(Thread.java:748)

if you have a "genuine" UNO, then check this out https://github.com/NicoHood/HoodLoader2

The UNO can't be a Keyboard. It doesn't have a real USB connection. It has a serial connection that passes through a UART to USB converter.
You cannot use the UNO as a keyboard.
Instead you need one of the boards that has a real USB connection, such as the Arduino Leonardo or any of the other ATMega32U4-based boards.

Thanks for that clarification!  Would Arduino Mega 2560 work?

No. That doesn't use the ATMega32U4 either. Arduino Micro or Leonardo

if the UNO uses a ATMega16U4 as a USB to serial converter, then it is doable .... you would have to reprogram the ATMega16U4


text:
Weird behavior of variables when replacing for loops with if statement
See the picture of serial monitor showing I get a large number, 4 billion, when I multiply two called functions together. It always happens after 53 if I change the amount the if statement counts to. I serial monitored the if statement and it counts to 600 then down then up and repeats good and the sensorValue stays the same.  I get rid of the division in y and I put it all in the for loop and still get a large number. My purpose is to fade pin and adjusts analogWrite at same time. It adjusts but does not fade. Does replacing for loop with if statement or calling to many functions create a bug.

int analogInPin = A0;
int analogOutPin3 = 3;

int sensorValue;

int i = 0;
int a;
int y;

void sens(int &sensorValue){
  sensorValue = (((long)analogRead(analogInPin)*255)/1023);
}

void inOut(int &i){
  if (i > -1){
    i = i + a;
  if (i == 0){
     a = 1;
  }
  if (i == 600){
    a = -1;
  }
  return i;
 }
}

void updateFade(){
  sens(sensorValue);
  inOut(i);
  unsigned long y = ((sensorValue*i)/600);
  Serial.println(sensorValue);
}

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

void loop() {
  updateFade();
  delay(100);
  analogWrite(3, y);
}

Signed into unsigned doesn't go. If i is -1 then what is y going to be?

y will always be 0 because the one calculated inside that function is local to it and dies when the function ends without having ever been used.  So the y that is used int he analogWrite in loop will always be 0.

If I can make another unrelated suggestion, your sens function doesn't need to take any parameters.  It could just be sens().  Since sensorValue is global, you can modify it and access it from anywhere in the program.  You don't need to pass it around as an argument.  You only need the whole pass by reference thing if you are trying to modify local variables in one function from another function.  But that's not what you're doing here.  You've got a global variable.  Same thing with your inOut function.  i is global, so you can just use it.  You don't need to pass it around.

these are all the same integer .... binary 1111 1111 1111 1111 1111 1111 1100 1010 == hexadecimal FFFFFFCA  == unsigned decimal 4294967242 == signed decimal -54

You define i,y,i as global variables so there is no need to hand them over to different functions. They can be accessed and changed in all parts of your program.
define instead of
int y;

change to
long y;

and change
 void inOut(int &i){

to
void inOut(){

and remove
   return i;// Its a global var

change the line
unsigned long y = ((sensorValue*i)/600);

to
y = ((sensorValue*i)/600);

Try to avoid the same names for global and local vars. It might happen that the compiler handles it as a redefinition, which might lead to all sort of trouble in complex programs. (Also for you if you look onto an ill documented code some months later)And get rid of the delay it stops processing (also your subroutines) see Blinkwithoutdelay how to do it properly ArduinoIDE->file->examples->2 Digital->Blinkwithoutdelay

Thanks for the help, this is my working code.  I changed things to long, got rid of some long's, stopped passing variables, and forced number in sensorValue to be long.  It now counts up and down were I set the potentiometer every minute.

int analogInPin = A0;
int analogOutPin3 = 3;

long sensorValue;

int i = 0;
int a;
long y;

void sens(){
  sensorValue = ((analogRead(analogInPin)*255L)/1023); //force 255 to be long
}

void inOut(){
  if (i > -1){
    i = i + a;
  if (i == 0){
     a = 1;
  }
  if (i == 600){
    a = -1;
  }
 }
}

void updateFade(){
  sens();
  inOut();
  y = ((sensorValue*i)/600);
  Serial.println(y);
}

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

void loop() {
  updateFade();
  delay(100);
  analogWrite(3, y);
}