text:
Programming NEMA 17 2 Phase, 4 Wire Stepper Motor
I have successfully programmed the Stepper Motor 28BYJ-48 with ULN2003 driver using the code below. But then I replaced the 28BJY-48 with a NEMA 17 Motor then it won't work anymore. I researched that the 28BJY-48 is a 4 phase stepper motor and the NEMA 17 is a 2 phase stepper motor. Is there a difference on how should I programmed a 2 phase stepper motor from a 4 phase stepper motor?
#define A        2                     // the pin connected to the wire A of the coil A (or to the H-bridge pin controlling the same wire)
#define A_bar    3                     // the pin connected to the wire A- of the coil A (or to the H-bridge pin controlling the same wire)
#define B        4                     // the pin connected to the wire B of the coil A (or to the H-bridge pin controlling the same wire)
#define B_bar    5                     // the pin connected to the wire B- of the coil A (or to the H-bridge pin controlling the same wire)
#define x        4000                  // smaller values may make the motor produce more speed and less torque
#define stepsPerRevolution 200         // you can the number of steps required to make a complete revolution in the data sheet of your motor

void setup() {
  pinMode(A, OUTPUT);
  pinMode(A_bar, OUTPUT);
  pinMode(B, OUTPUT);
  pinMode(B_bar, OUTPUT);
}

void loop() {
  for (int i = 0; i < (stepsPerRevolution/4) ; i++) {
    digitalWrite(A, HIGH);
    digitalWrite(A_bar, LOW);
    digitalWrite(B, HIGH);
    digitalWrite(B_bar, LOW);
    delayMicroseconds (x);

    digitalWrite(A, LOW);
    digitalWrite(A_bar, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(B_bar, LOW);
    delayMicroseconds (x);

    digitalWrite(A, LOW);
    digitalWrite(A_bar, HIGH);
    digitalWrite(B, LOW);
    digitalWrite(B_bar, HIGH);
    delayMicroseconds (x);

    digitalWrite(A, HIGH);
    digitalWrite(A_bar, LOW);
    digitalWrite(B, LOW);
    digitalWrite(B_bar, HIGH);
    delayMicroseconds (x);
  }

  /*// Counter Direction
  for (int i = 0; i < (stepsPerRevolution/4); i++) {
    digitalWrite(A, HIGH);
    digitalWrite(A_bar, LOW);
    digitalWrite(B, LOW);
    digitalWrite(B_bar, HIGH);
    delayMicroseconds (x);

    digitalWrite(A, LOW);
    digitalWrite(A_bar, HIGH);
    digitalWrite(B, LOW);
    digitalWrite(B_bar, HIGH);
    delayMicroseconds (x);

    digitalWrite(A, LOW);
    digitalWrite(A_bar, HIGH);
    digitalWrite(B, HIGH);
    digitalWrite(B_bar, LOW);
    delayMicroseconds (x);

    digitalWrite(A, HIGH);
    digitalWrite(A_bar, LOW);
    digitalWrite(B, HIGH);
    digitalWrite(B_bar, LOW);
    delayMicroseconds (x);
  }
  delay(1000);*/
}

I changed the stepsPerRevolution to 200 for NEMA 17 and 32 for the 28BJY-48. NEMA 17 does not work.

Is there a difference on how should I programmed a 2 phase stepper motor from a 4 phase stepper motor? .... it is up to you to research the differences between the two ... once you have the information, the solution may become obvious

You can’t use a ULN2003 to drive a bi-polar stepper motor.

I see that others used L293D, so I can use that with the same code?


text:
Using INT2/3 on Arduino Micro (Atmega32u4)
My project is using almost all the pins on this board and I require an interrupt pin to read radio state (rather than polling). I'm using I2C, so that leaves INT2 and INT3, which are the TX and RX pins for USB/Serial1. According to the documentation, disabling serial, using Serial.end(), should allow me to take control of those pins. However, using the pins as interrupt handlers doesn't work. Here is a sample sketch:
static int ledpin = 13;
volatile byte state = LOW;

void func()
{
  state = !state;
}

void setup() {
  Serial.end();

  pinMode(ledpin, OUTPUT);

  // INT2
  pinMode(0, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(0), func, CHANGE);

  // INT3
  pinMode(1, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(1), func, CHANGE);
}

void loop() {
  digitalWrite(ledpin, state);
}

This example is mostly copy-pasted from the Arduino website. All the other interrupts work fine, only INT2 and INT3 don't.
Is there a way to use these interrupts?

How do you know that they don't work? If both interrupts are fired, then you can't notice it. "Serial" is the serial port via USB to the computer. "Serial1" is the hardware serial port at pin 0 and 1. If you don't use "Serial1", then pin 0 and 1 are not yet initialized as serial port and they are normal digital pins like any other. Remove the Serial.end. It should work, you could increment a byte and print the byte to the serial monitor (using the USB "Serial"). There are also pcint interrupts: http://www.pighixxx.com/test/portfolio-items/micro/ Is !LOW the same as HIGH, or is that a guess.

You problem isn't with your pins or code, but with debouncing the signals. I've changed the "func()" method to read:
void func()
{
  static uint32_t lastChange = 0; // Note millis() don't change inside ISR, but can be read
  if (millis() - lastChange > 100)
  {
    state = !state;
  }
  lastChange = millis(); // Set new value
}

which will ignore spurious interrupts if they occur within 100ms of each other. This solves the issue that you are seeing, I've tested it on an Arduino Micro I have lying around.

/*
   2019-08-29 Nicola Bernardelli. Going through the ATmega32U4 Datasheet and applying the steps
   to set up the analog comparator on a Pro Micro board.

   While doing this, I understand that the Analog to Digital Converter must be switched off.
   So, if you are needing to stick with ATmega32U4 but also need the ADC (as I do in my current project), you might have to add a
   circuit with a comparator, e.g. LM393 or LM339, instead of using the built-in Analog Comparator.
   Disabling this interrupt and reactivating the ADC has not been added to this sketch.

   Also, a "real" handling of the interrupt-triggered event has not been added and the sketch leaves the possibility of a very fast
   succession of interrupt requests. You might want to check the (currently only one) answer given here:
   https://arduino.stackexchange.com/questions/49195/using-int2-3-on-arduino-micro-atmega32u4

   [I wanted to ask/contribute here https://arduino.stackexchange.com/questions/17480/using-analog-comparator-on-atmega32u4
   (I see that it is 3 years 9 months old but it's still "searchable" on the Internet, which is how I went there. I think that keeping the
   information under that pertinent title is a better option than opening a new thread.)
   So I created an account, but it turns out that I don't have enough "reputation" there to comment, so I wrote into the edit field
   available to give an answer, and that did not work out either:
   "Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed,
   posting an answer now requires 10 reputation on this site (the association bonus does not count)."
   So... pretty much chessmate. Well... their board, their rules.]
*/

#include "Arduino.h"

#ifndef ARDUINO_AVR_PROMICRO
#error This sketch is meant for the Arduino Pro Micro, it is based on the ATmega32U4 Datasheet and the Pro Micro pinout. \
       You might decide to try it on a different ATmega32U4-based board if the pins choice is OK (please check/change the LED pin number).
#endif

#define THIS_BOARD_LED_BUILTIN 17
#define LED_ON_DURATION 200

volatile bool analogCompInterruptToggled;
unsigned long millisLastTrigger;

void setup() {

  Serial.begin(9600);

  analogCompInterruptToggled = false;
  millisLastTrigger = 0;
  pinMode(THIS_BOARD_LED_BUILTIN, OUTPUT);
  digitalWrite(THIS_BOARD_LED_BUILTIN, HIGH);

  /* As per Atmega32U4 Datasheet starting pag 293 (and linked pages). */

  PRR0 &= ~bit(PRADC); // Disables power reduction for the ADC in order to use the ADC input MUX.

  /*
     ACME in ADCSRB: When this bit is written logic one and the ADC is switched off (ADEN in ADCSRA is zero),
     the ADC multiplexer is connected to the negative input to the Analog Comparator. When this bit is written
     logic zero, the Bandgap reference is connected to the negative input of the Analog Comparator
  */
  ADCSRA &= ~bit(ADEN); /* Switches off the ADC so we can use the Muxer with the Analog Comparator instead of the ADC. */
  ADCSRB |= bit(ACME);  /* With the line above => the ADC multiplexer is connected to the negative input of the Analog Comparator. */
                        /* See table at page 295: ACME 0 or (ACME 1 and ADEN 1) => bandgap ref as the Analog Comparator Negative Input. */

  /*                                        ******** A0 NEGATIVE INPUT ********
     Let's select pin ADC7 = A0 as the negative input to the Analog Comparator, as per pag 295 of the ATmega32U4 DataSheet:
     ACME to 1 done above, ADEN to 0 done above, MUX2..0 to 111.
  */
  ADMUX |= 0b00000111;

  /*                                        ******** D7 POSITIVE INPUT ********
     When this bit is set, a fixed bandgap reference voltage replaces the positive input to the Analog Comparator.
     When this bit is cleared, AIN0 is applied to the positive input of the Analog Comparator.
  */
  ACSR &= ~bit(ACBG); // AIN0 = D7 => positive input of the Analog Comparator

  /* Pages 294-295 of the ATmega32U4 Datasheet. */
  ACSR &= ~bit(ACIC); /* Analog Comparator Input Capture disabled. */

  /* Comparator Interrupt trigger mode. 0-0 => TOGGLE, meaning any change; 1-0 => FALLING; 1-1 => RISING). */
  // ACSR &= ~bit(ACIS1); ACSR &= ~bit(ACIS0); // TOGGLE
  // ACSR |= bit(ACIS1);  ACSR &= ~bit(ACIS0); // FALLING
     ACSR |= bit(ACIS1);  ACSR |= bit(ACIS0);  // RISING

  DIDR1 &= ~bit(AIN0D); /* It's actually the rightmost bit, we could write DIDR1 &= ~1 */
  /*
     When this bit is written logic one, the digital input buffer on the AIN0 pin is disabled. [...]
     When an analog signal is applied to the AIN0 pin and the digital input from this pin is not needed,
     this bit should be written logic one to reduce power consumption in the digital input buffer.
  */

  ACSR |= bit(ACIE);
  SREG |= bit(SREG_I);
  /* When the ACIE bit is written logic one and the I-bit in the Status Register is set,
     the Analog Comparator interrupt is activated. When written logic zero, the interrupt is disabled.
  */
}

ISR(ANALOG_COMP_vect) {
  analogCompInterruptToggled = true;
}

void loop() {
  // put your main code here, to run repeatedly:
  if (analogCompInterruptToggled) {
    analogCompInterruptToggled = false;
    digitalWrite(THIS_BOARD_LED_BUILTIN, LOW);
    millisLastTrigger = millis();
    Serial.print("toggled - millis() == ");
    Serial.println(millisLastTrigger);
  }
  else if (millis() > millisLastTrigger + LED_ON_DURATION) {
    digitalWrite(THIS_BOARD_LED_BUILTIN, HIGH);
  }
}

source: Stack Exchange

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

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

sort: votes


text:
Code uploads to Due and fails to execute but runs on Redboard
I have run into this issue where my code will upload to my Due but fails to execute. I have verified the code works on a SparkFun Redboard. The only code difference is that the SPI pin assignments have been appropriately changed. My code, for initial testing purposes, can run without any sort of attachments or additional boards. I do use or rather will be using SPI communication when I do wire up all of the instruments. The code currently handles not having anything connected just fine. The expected output as provided by running on the Redboard is below.

Initially I thought that my code was running on the Due and failing to communicate serially, but when I tried to implement a simple blink routine near the beginning of the loop and even some things during setup, it became clear that the code was failing to make it through the "setup" function. I couldn't even get a serial print from the second line of the setup function. It is very clear that the code fully uploads based on both the IDE and the Rx/Tx LEDs on the board. I am using the correct port, and I am using the correct board selection and USB port on the board (the programming port nearest to the barrel plug jack).
I came across a number of posts and they either didn't address my issue or they didn't actually come to a conclusion. I did find some very simple test code post in a different topic (below). This code does run. I have also successfully run the "Blink" example code on the Due.
byte count = 0;

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

void loop() {
  Serial.print ("Count = ");
  Serial.println (count);
  count++;
  delay(500);
}

It was brought to my attention that there may be some libraries that don't play well with the Due, but even when I removed all immediately unnecessary libraries, I was unable to get the code to run on the Due.
The actual code for the project is shown below. There is some commented-out code that I tried to use for debugging. Also, I have split up the code into separate CPP and header files as that was what I was taught to do in college.
Does anyone know what is going on here? Does anyone know of a fix or workaround?
The code is provided in the follow order:
fluidized_bed_test.ino
Blower.cpp
Blower.h
Heater.cpp
Heater.h
Thermocouple.cpp
Thermocouple.h
control.cpp
control.h
fluidized_bed_test.h
fluidized_bed_test.ino
#pragma once
#include "Thermocouple.h"
#include "Heater.h"
#include "Blower.h"
#include "fluidized_bed_test.h"

#define MAX_MESSAGE_LEN 50

Thermocouple therm1(MOSIPin,MISOPin,CLKPin,CHIPSEL1,DRDYPIN1);
Thermocouple therm2(MOSIPin,MISOPin,CLKPin,CHIPSEL2,DRDYPIN2);
Thermocouple therm3(MOSIPin,MISOPin,CLKPin,CHIPSEL3,DRDYPIN3);
Heater heater(HEATERPIN);
Blower blower(BLOWERPIN);

void setup()
{
  Serial.begin(115200);
//  while (!Serial){}
  Serial.print("Shall we begin");
  SPI.begin();
  pinMode( MISOPin, INPUT );
  pinMode( MOSIPin, OUTPUT );
  pinMode( DRDYPIN1, INPUT );
  pinMode( CHIPSEL1, OUTPUT ); // Thermocouple 1
  pinMode( DRDYPIN2, INPUT );
  pinMode( CHIPSEL2, OUTPUT ); // Thermocouple 2
  pinMode( DRDYPIN3, INPUT );
  pinMode( CHIPSEL3, OUTPUT ); // Thermocouple 3
  pinMode( HEATERPIN, OUTPUT); // Heater
//  pinMode(LED_BUILTIN, OUTPUT);
//  pinMode(13, OUTPUT);

  therm1.setFaultMask();
  therm1.setBaseConfig();
  therm1.setColdOffset();
  therm1.setTemperatureFault();

  therm2.setFaultMask();
  therm2.setBaseConfig();
  therm2.setColdOffset();
  therm2.setTemperatureFault();

  therm3.setFaultMask();
  therm3.setBaseConfig();
  therm3.setColdOffset();
  therm3.setTemperatureFault();

  heater.setControl(0);
  blower.setControl(1);
  blower.setBlower(1);
  blower.setPID(255);
//  digitalWrite(LED_BUILTIN, LOW); //added to see if executing at all
//  delay(5000);
//  digitalWrite(LED_BUILTIN, HIGH); //added to see if executing at all
//  delay(5000);
  delay(200);
}

void loop()
{
  static float temperature1 = 0;
  static float temperature2 = 0;
  static float temperature3 = 0;
  static int blower_pid = 255;
  static int new_blower_pid = -1;
  static int remaining_char = 0;
  static int i = 0;
  static char inByte = 0;
  static char incoming_message[MAX_MESSAGE_LEN];
  temperature1 = therm1.getTemp();
  temperature2 = therm2.getTemp();
  temperature3 = therm3.getTemp();

  digitalWrite(LED_BUILTIN, LOW); //added to see if executing at all
//  delay(5000);

//  static int j = 0;
//  while(j < 10)
//  {
//  digitalWrite(LED_BUILTIN, LOW); //added to see if executing at all
//  delay(500);
//  digitalWrite(LED_BUILTIN, HIGH); //added to see if executing at all
//  delay(500);
//  j++;
//    }

 // Retrieve Thermocouple 1 temps
  Serial.println("Thermocouple 1 Temperature");
  Serial.println(temperature1);
  Serial.println("Cold Junction 1 Temperature");
  Serial.println(therm1.getColdTemp());

 // Retrieve Thermocouple 2 temps
  Serial.println("Thermocouple 2 Temperature");
  Serial.println(temperature2);
  Serial.println("Cold Junction 2 Temperature");
  Serial.println(therm2.getColdTemp());

// Retrieve Thermocouple 3 temps
  Serial.println("Thermocouple 3 Temperature");
  Serial.println(temperature3);
  Serial.println("Cold Junction 3 Temperature");
  Serial.println(therm3.getColdTemp());

  i = 0;

  while ( Serial.available() )
  {
    inByte = Serial.read();

    if ( inByte != '\n' && (i < MAX_MESSAGE_LEN - 1) )
    {
      incoming_message[i] = inByte;
      i++;
    }
    else
    {
      incoming_message[i] = '\0';
    }
  }
  new_blower_pid = atoi(incoming_message);
  digitalWrite(LED_BUILTIN, HIGH); //added to see if execturing at all
  delay(1000);
}

Blower.cpp
#pragma once
#include "Blower.h"

Blower::Blower(int pin)
{
  pinNum = pin;
  blowerState = 0;
  pidState = 0;
  pidValue = 255;
}

void Blower::setBlower( boolean state )
{
  blowerState = state;
  updateBlower();
}

void Blower::setControl(boolean state )
{
  pidState = state;
  updateBlower();
}

void Blower::setPID( int pid )
{
  pidValue = pid;
  updateBlower();
}

boolean Blower::isOn()
{
  return blowerState;
}

boolean Blower::getControl()
{
  return pidState;
}

int Blower::getPIDValue()
{
  return pidValue;
}

void Blower::updateBlower()
{
  if(blowerState)
  {
    if(pidState)
    {
      analogWrite(pinNum,pidValue);
    }
    else
    {
      analogWrite(pinNum,255);
    }
  }
  else
  {
    analogWrite(pinNum,255);
  }
}

Blower.h
#pragma once
#if ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif

class Blower
{
  public:
    Blower( int pin);
    void setBlower(boolean = false);
    void setControl(boolean = false);
    void setPID(int pid = 255);
    boolean isOn();
    boolean getPidState();
    boolean getControl();
    int getPIDValue();

  private:
    void updateBlower();

    boolean blowerState;
    boolean pidState;
    int pidValue;
    int pinNum;
};

Heater.cpp
#pragma once
#include "Heater.h"

Heater::Heater(int pin)
{
  pinNum = pin;
  heaterState = 0;
  pidState = 0;
  pidValue = 255;
}

void Heater::setHeater( boolean state )
{
  heaterState = state;
  updateHeater();
}

void Heater::setControl(boolean state )
{
  pidState = state;
  updateHeater();
}

void Heater::setPID( int pid )
{
  pidValue = pid;
  updateHeater();
}

boolean Heater::isOn()
{
  return heaterState;
}

boolean Heater::getControl()
{
  return pidState;
}

int Heater::getPIDValue()
{
  return pidValue;
}

void Heater::updateHeater()
{
  if(heaterState)
  {
    if(pidState)
    {
      analogWrite(pinNum,pidValue);
    }
    else
    {
      analogWrite(pinNum,255);
    }
  }
  else
  {
    analogWrite(pinNum,255);
  }
}

Heater.h
#pragma once
#if ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif

class Heater
{
  public:
    Heater( int pin);
    void setHeater(boolean = false);
    void setControl(boolean = false);
    void setPID(int pid = 255);
    boolean isOn();
    boolean getPidState();
    boolean getControl();
    int getPIDValue();

  private:
    void updateHeater();

    boolean heaterState;
    boolean pidState;
    int pidValue;
    int pinNum;
};

Thermocouple.cpp
#pragma once
#include "Thermocouple.h"

Thermocouple::Thermocouple(int mosiPin,int misoPin,int clkPin, int chslctPin, int drdy)
{
  SPI.begin();
  MOSI = mosiPin;
  MISO = misoPin;
  CLK = clkPin;
  CHSLCT = chslctPin;
  DRDY = drdy;
}

double Thermocouple::getTemp(int unitTemp)
{
  switch(unitTemp)
  {
    case 0:
      return readThermocouple();
      break;
    case 1:
      return readThermocouple() + 273.15;
      break;
    case 2:
      return readThermocouple()*1.8 + 32;
      break;
    case 3:
      return (readThermocouple() + 273.15) * 1.8 - 32;
      break;
  }
}

double Thermocouple::binaryTempConvert( int binaryResult, int byteNumber )
{
  double decimalAns = 0;
  int placeHolder = 0;
  int numbit = 0;
  while (numbit <= 7 )
  {
    placeHolder = 0;
    placeHolder = binaryResult & int(pow(2, numbit)+.5);
    if ( placeHolder != 0 )
    {
      if ( byteNumber == 3 && numbit <= 5 )
      {
      }
      else if ( numbit == 7 && byteNumber == 1 )
      {
        decimalAns = decimalAns*(-1);
      }
      else
      {
        decimalAns = decimalAns + pow(2,(((8*(4-byteNumber))-1)-(7-numbit)-12));

      }

    }
    numbit = numbit+1;
  }
  return decimalAns;
}

/*double Thermocouple::readThermocouple()
{
  double result = 0;
  unsigned int preresult1 = 0;
  unsigned int preresult2 = 0;
  unsigned int preresult3 = 0;

  SPI.beginTransaction(SPISettings(500000,MSBFIRST,SPI_MODE1));

  digitalWrite( CHSLCT, LOW );

  SPI.transfer(rLinThermByte2);
  preresult1 = SPI.transfer(0);

  SPI.transfer(rLinThermByte1);
  preresult2 = SPI.transfer(0);

  SPI.transfer(rLinThermByte0);
  preresult3 = SPI.transfer(0);

  digitalWrite( chipselectPin1, HIGH );
  SPI.endTransaction();

  result = binaryTempConvert( preresult1, 1 );
  result = result + binaryTempConvert( preresult2, 2 );
  result = result + binaryTempConvert( preresult3, 3 );

  return result;

}*/

double Thermocouple::readThermocouple()
{
  byte dataToSend;
  double result = 0;
  unsigned int preresult1 = 0;
  unsigned int preresult2 = 0;
  unsigned int preresult3 = 0;
  unsigned int preresult[] = {0,0,0};
  int i = 0;

  SPI.beginTransaction(SPISettings(500000,MSBFIRST,SPI_MODE1));

  /*digitalWrite( CHSLCT, LOW );

  dataToSend = rLinThermByte2;
  SPI.transfer(rLinThermByte2);
  preresult1 = SPI.transfer(0);

  digitalWrite( CHSLCT, HIGH );

  digitalWrite( CHSLCT, LOW );

  dataToSend = rLinThermByte1;
  SPI.transfer(rLinThermByte1);
  preresult2 = SPI.transfer(0);

  digitalWrite( CHSLCT, HIGH );

  digitalWrite( CHSLCT, LOW );

  dataToSend = rLinThermByte0;
  SPI.transfer(rLinThermByte0);
  preresult3 = SPI.transfer(0);

  digitalWrite( CHSLCT, HIGH );
  SPI.endTransaction();

  result = binaryTempConvert( preresult1, 1 );
  result = result + binaryTempConvert( preresult2, 2 );
  result = result + binaryTempConvert( preresult3, 3 );*/

  for( i; i<3; i++)
  {
    digitalWrite(CHSLCT, LOW);
    SPI.transfer(rLinThermByte2 + byte(i));
    preresult[i] = SPI.transfer(0);
    digitalWrite(CHSLCT,HIGH);
  }
  for( i = 0; i<3; i++)
  {
    result += binaryTempConvert(preresult[i],i+1);
  }
  lastTemp = result;
  return result;

}

bool Thermocouple::isReady()
{
  return !digitalRead(DRDY);
}

void Thermocouple::writeRegister( byte thisRegister, byte thisValue )
{
   digitalWrite( CHSLCT, LOW );
  SPI.beginTransaction(SPISettings(1000000,MSBFIRST,SPI_MODE1));

  SPI.transfer(thisRegister);
  SPI.transfer(thisValue);

  digitalWrite( CHSLCT, HIGH );
  SPI.endTransaction();

}

unsigned int Thermocouple::readRegister( byte thisRegister )
{

  byte inByte = 0;
  unsigned int result = 0;

  digitalWrite( CHSLCT, LOW );

  byte dataToSend = thisRegister;
  SPI.beginTransaction(SPISettings(1000000,MSBFIRST,SPI_MODE1));
  SPI.transfer(dataToSend);
  result = SPI.transfer(0b10101010);

  SPI.endTransaction();
  digitalWrite( CHSLCT, HIGH );

  return result;
}

void Thermocouple::setFaultMask(byte regFault)
{
  writeRegister(wfaultMask,regFault);
}

void Thermocouple::setBaseConfig(byte regOne, byte regTwo )
{
  writeRegister(wCNfig0,regOne);
  writeRegister(wCNfig1,regTwo);
}

void Thermocouple::setTemperatureFault(int lowCold, int highCold, double lowHot, double highHot )
{
  int i = 0;
  int value = 0;
  double placeHold = 0;
  double absTemp = abs(lowHot);
  char binOne = 0;
  char binTwo = 0;
  if( lowHot > -2074.9375 || lowHot < 2074.9375 )
  {
    for( i = -4; i < 11; i++)
    {

      if( abs(absTemp - placeHold) > abs(absTemp - placeHold + pow(2,i)) )
      {
        placeHold += pow(2,i);
        value = (value << 1) | 0b00000001;
      }
    }
    if( lowHot < 0 )
      value = value | 0b1000000000000000;
  }
  binOne = char(value >> 8);
  binTwo = char(value & 0b0000000011111111);
  writeRegister(wLinThermLowFaultThreshMSB, binOne);
  writeRegister(wLinThermLowFaultThreshLSB, binTwo);

  value = 0;
  placeHold = 0;
  absTemp = abs(highHot);
  binOne = 0;
  binTwo = 0;

  if( highHot > -2074.9375 || highHot < 2074.9375 )
  {
    for( i = -4; i < 11; i++)
    {

      if( abs(absTemp - placeHold) > abs(absTemp - placeHold + pow(2,i)) )
      {
        placeHold += pow(2,i);
        value = (value << 1) | 0b00000001;
      }
    }
    if( highHot < 0 )
      value = value | 0b1000000000000000;
  }
  binOne = char(value >> 8);
  binTwo = char(value & 0b0000000011111111);
  writeRegister(wLinThermHighFaultThreshMSB, binOne);
  writeRegister(wLinThermHighFaultThreshLSB, binTwo);

  binOne = 0;
  binTwo = 0;

  if( lowCold >= 0b11111111 && highCold <= 0b01111111 && highCold > lowCold )
  {
    binOne = char(lowCold);
    binTwo = char(highCold);

    writeRegister(wColdLowFaultThresh,binOne);
    writeRegister(wColdHighFaultThresh,binTwo);
  }

}

void Thermocouple::setColdOffset(double temp)
{
  int i = 0;
  char value = 0;
  double placeHold;
  double absTemp = abs(temp);
  if( temp > -7.9375 || temp < 7.9375 )
  {
    for( i = 2; i > -5; i--)
    {
      if( abs(absTemp - placeHold) > abs(absTemp - placeHold + pow(2,i)) )
      {
        placeHold += pow(2,i);
        value = value | int(pow(2,i+4)+.5);
      }
    }
    if( temp < 0 )
      value = value | 0b10000000;
  }
  writeRegister(wColdOffset, value);
}

double Thermocouple::getColdOffset()
{
  int placeHold = 0;
  int i;
  double result = 0;
  char regVal = readRegister(rColdOffset);
  for( i=0; i<7; i++)
  {
    placeHold = int(pow(2,i)+.5);
    if( regVal & placeHold )
      result += pow(2,i-4);
  }
  if( regVal & 0b10000000 )
    result *= (-1);
  return result;
}

double Thermocouple::getColdTemp()
{
  int i = 0;
  int tempReading = byte( readRegister(rColdTempMSB) );
  tempReading = tempReading << 8;
  tempReading = tempReading | byte( readRegister(rColdTempLSB) );
  double result = 0;

  for( i=-6;i<7;i++)
  {
    if (  tempReading & int(pow(2,i+8)+.5) )
    {
      result += pow(2,i);
    }
  }
  return result;
}

double Thermocouple::getLatestTemp()
{
  return lastTemp;
}

Thermocouple.h
#pragma once
#if ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif
#include <SPI.h>

// memory register WRITE addresses of MAX31856 thermocouple board
#define wCNfig0 0x80
#define wCNfig1 0x81
#define wfaultMask 0x82
#define wColdHighFaultThresh 0x83
#define wColdLowFaultThresh 0x84
#define wLinThermHighFaultThreshMSB 0x85
#define wLinThermHighFaultThreshLSB 0x86
#define wLinThermLowFaultThreshMSB 0x87
#define wLinThermLowFaultThreshLSB 0x88
#define wColdOffset 0x89
#define wColdTempMSB 0x8A
#define wColdTempLSB 0x8B

// memory register READ addresses of MAX31856 thermocouple board
#define rCNfig0 0x00
#define rCNfig1 0x01
#define rfaultMask 0x02
#define rColdHighFaultThresh 0x03
#define rColdLowFaultThresh 0x04
#define rLinThermHighFaultThreshMSB 0x05
#define rLinThermHighFaultThreshLSB 0x06
#define rLinThermLowFaultThreshMSB 0x07
#define rLinThermLowFaultThreshLSB 0x08
#define rColdOffset 0x09
#define rColdTempMSB 0x0A
#define rColdTempLSB 0x0B
#define rLinThermByte2 0x0C
#define rLinThermByte1 0x0D
#define rLinThermByte0 0x0E
#define rFaultStatus 0x0F
#ifndef THERMOCOUPLE_H
#define THERMOCOUPLE_H

class Thermocouple
{
  public:
    Thermocouple(int mosiPin,int misoPin,int clkPin, int chslctPin, int drdy);//{MOSI,MISO,CLK,CHSLCT,DRDY};
    double getTemp(int unitTemp = 0);
    double getLatestTemp();
    void setFaultMask(byte regFault = 0b00110011);
    void setBaseConfig(byte regOne = 0b10000010,byte regTwo = 0b00000011 );
    void setTemperatureFault(int lowCold = 0,int highCold = 50,double lowHot = 0,double highHot = 200);
    void setColdOffset(double temp = 0);
    double getColdOffset();
    double getColdTemp();
    bool isReady();

  private:
    unsigned int readRegister(byte);
    void writeRegister(byte,byte);
    double readThermocouple();
    double binaryTempConvert(int,int);
    double lastTemp;
    int MOSI,MISO,CLK,CHSLCT,DRDY;

};
#endif

control.cpp
#pragma once
#include "control.h"
// #include "Thermocouple.h"
// #include "Heater.cpp"
// #include "Blower.h"

void fluid_bed_control( Heater heater, Blower blower, double inlet_temp, double bed_temp)// double MAX_INLET_TEMP, double MAX_BED_TEMP, double MIN_BED_TEMP)
{
  if( inlet_temp > MAX_INLET_TEMP )
  {
    heater.setHeater(0);
    blower.setBlower(1);
  }
  else if( bed_temp > MAX_BED_TEMP )
  {
    heater.setHeater(0);
    blower.setBlower(1);
  }
  else if( bed_temp < MIN_BED_TEMP )
  {
    heater.setHeater(1);
    blower.setBlower(1);
  }

}

control.h
#pragma once
#include "Thermocouple.h"
#include "Heater.h"
#include "Blower.h"
#include "fluidized_bed_test.h"

void fluid_bed_control( Heater heater, Blower blower, double inlet_temp, double bed_temp);//, double max_inlet_temp, double max_bed_temp, double min_bed_temp);

fluidized_bed_test.h
#pragma once
//#include <TimerOne.h>
//#include <Chrono.h>
//#include <LightChrono.h>
#include <SPI.h>
//#include <LiquidCrystal.h>
//#include <Wire.h> // Include the I2C library (required)
//#include <SparkFunSX1509.h> // Include SX1509 library

#define MAX_INLET_TEMP 82.2
#define MIN_INLET_TEMP 68.0
#define MAX_BED_TEMP 72.0
#define MIN_BED_TEMP 68.0

// pinout of redboard

// #define scrnPin1 1
// #define scrnPin2 2
// #define scrnPin3 3
// #define scrnPin4 4
// #define scrnPin5 5
// #define scrnPin6 6
#define DRDYPIN3 5
#define CHIPSEL3 6
#define DRDYPIN2 7
#define CHIPSEL2 8
#define DRDYPIN1 9
#define CHIPSEL1 10
//#define MOSIPin 11
//#define MISOPin 12
//#define CLKPin 13
#define MOSIPin 75
#define MISOPin 74
#define CLKPin 76
// #define SCRNCOM A0
// #define FLOATPIN1 A1
// #define FLOATPIN2 A2
// #define VALVEPIN1 A3
// #define VALVEPIN2 A4
#define HEATERPIN 4
#define BLOWERPIN 3

// pinout of I2C board
// #define MOTORPIN1 20
// #define MOTORPIN2 21
// #define FAULTPIN1 22
// #define FAULTPIN2 23

struct ProcessState
{
  bool safetyFlag;
  bool fillState;
  bool firstTime;
  bool standBy;
  bool warmUp;
  bool pasteurize;
  bool coolDown;
  bool emptyState;
  bool standByEmpty;
};

What happens on the Due instead?

SPI on the Due is.... strange. There are multiple "channels" each using the same data / clock pins, but tied to specific chip select pins. Trying to use pins that aren't those specific chip select pins could have unwanted results. I don't know what those results will be, but I personally avoid the Due for anything, and especially anything where SPI is concerned.

@pmf Nothing happens on the due. There is no serial communication, even if I put the serial communication initialization and first serial print in the first two lines of the setup function. When I try to get the onboard LED to blink like in the "blink" sketch, nothing happens.

@Majenko So I have learned. I wish I knew that the Due was so difficult to deal with before I purchased it. Also the whole premise of having an "unrequired" pre-designated chip select (CS) pin is weird. Any other pin that can be switched be high and low can function as a CS pin.

Try putting a delay (of half a second or so) between Serial.begin() and the first print. Sometimes, the first characters are lost otherwise. I was able to get SPI to run on the Due, but that was some time ago.

When debugging with serial you should follow each print with a Serial.flush(); so that your program pauses until the message has actually been displayed, otherwise a crash later in the program will stop earlier messages from being displayed. Then put debugging between every non trivial line to see where it actually hangs.

@Majenko So I had tracked down the "bug" if that's what we want to call it. I don't know why it's a bug on the Due but not the Redboard though.  The things killing my program were the declarations of the global Thermocouple objects. I'm guessing it has something to do with the SPI.begin() inside the constructor of the class definition. I instead made a function that returns a new object which is set to a static variable in loop(). Why the Redboard doesn't have this issue is beyond me. Do either of you have any idea why the Redboard doesn't have this issue? I will try serial.flush() as well.

It is probably, yes, because the begin is in a constructor. One basic rule of Arduino coding is never put code that interacts with hardware in a constructor because that will run before the Arduino init routines which may break (entirely depending on the board) the hardware config that was done in the constructor.

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


text:
Confusion over Transistors for a switching circuit with an Arduino Mega 2560
Apologies if this is a stupid question asked by a noob, but I've looked around to try and find the answer and just can't work it out.
Basically, I'm making a project on thingiverse (Glitch's MK2 Stargate), and I've tried all sorts of different transistors with my circuit, I just can't get it to work properly.
Could you please advise which Transistor would work for the following circuit:

It's a basic thing, but the plan I was originally working from on thingiverse called for BC548BU transistors, however, the LEDs they were using were surface mount, and I am trying the same thing with 3mm standard LEDs. The BC548BU didn't work right on the normal LEDs.
I'm a total noob with this, but I've been trying to match the Base pin on the Transistor voltage output of my Arduino, but not sure if I'm doing the right thing. Can anybody help?
Thanks
-Dave
p.s. I have a load of transistors already (listed below), if any of these work, that would be great, if not, I will order the correct ones. The only one that seemed to match Data with the BC548 is the S9014, but it didn't seem to work at all, unless my understanding of the wiring of Transistors needs adjustment.

do you have ground of the arduino connected to anywhere in the circuit?

Not to the LED circuit no, just through its own PSU's ground. Should I be grounding it like that?

I thought the issue might be that my Mega 2560 is 3.3V on the digital, but the 584 is 5V base. The original circuit was for the Uno.

You cannot create the required voltage difference between base and emitter for switching when there is only a single electrical connection on the entire circuit.

But aren't the digital pins outputs? i.e, it gives the base 5V from the Arduino which then 'turns the switch' on the transistor which then turns the LED circuit on. I'm not saying you're wrong obviously, just trying to get an understanding.

Don't forget to add a resistor between the digital pin, and the transistor.

Thankyou, I am working it all out now, I've never done electronics like this before - as you can probably tell.

A transistor amplifies current, not voltage.
The first thing to check is the current of your LEDs. In your current configuration, it is between 25 and 30 mA. This is too high for most LEDs. Check the datasheet of your LEDs for the actual forward voltage, and current rating.
To calculate the value for the resistor in your circuit, use Kirchhoff's and Ohm's laws. According to Kirchhoff: VResistor + 3 VLED = 12 V. Let's assume that the LED's forward voltage drop VLED = 1.8 V. This means that VResistor = 12 V - 3 VLED = 6.6 V. Ohm's law will then tell you the relationship between the voltage across the resistor and the current through it: R = VResistor / I. The current through the resistor is the same as the current through the LEDs. Let's assume that this is 20 mA. Therefore: R = VResistor / I = 6.6 V / 0.020 A = 330 Ω.
The next thing to calculate is the resistor between the Arduino and the base of the transistor. As mentioned before: the voltage on the base does not matter, the current does. You want to use the transistor as a switch, so you have to drive it into saturation. As a general rule of thumb, you want the base current to be a tenth of the collector current in that case: IBase = ICollector / 10. The current through the collector is the same as the current through the LEDs, so IBase = 20 mA / 10 = 2 mA.
In a similar way as before, we can calculate the base resistor: VResistor + VBase-Emitter = VArduino. The voltage of the Arduino pin is most likely 5 V, and the Base-Emitter voltage of a silicon transistor is around 700 mV (look it up in the datasheet): VResistor = 5 V - 0.7 V = 4.3 V. Then use Ohm's law again to calculate the resistor value: RBase = VResistor / IBase = 4.3 V / 0.002 A = 2150 Ω ≈ 2.2 kΩ.
The current has to flow through the base to the emitter. For current to flow, you need at least two connections: current flows from the Arduino pin, through the transistor, to ground. You have to connect the emitter of the transistor to the Arduino's ground.
You can use pretty much any normal transistor that has a maximum collector current that is larger than the LED current, and a maximum collector-emitter voltage greater than your power supply.

I used https://www.kitronik.co.uk/blog/led-resistor-value-calculator/ to get the resistor value, and I've just double checked and it tells me that 3 in series, powered by a 12V power supply would need a 220Ohm resistor in line.
I will look into the calculations that you've sent to try and work it all out. Thankyou for your response.

@DavidRobilliard: the calculator you used is for LEDs in parallel, you have your LEDs in series. Running LEDs in parallel on a single resistor is not recommended.

Hi, I have tried it on http://led.linear1.org/led.wiz and it agrees with you about a 330Ohm, my mistake, sorry.

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


text:
How to store an array of doubles? As array of doubles, Strings or const char *? Then convert back to use?
This seems like an old, solved problem, but I can't find any simple answers.
I'm reading latitude and longitude data as Strings from a file (about 50 points), but they are really double float numbers.
First, I want to find the min/max ranges.   Then, later, I want to do some calculations on them.  I don't really want to keep reading the file, so I want to put them in an array.  But no matter what kind of array I use (3 examples below), the program crashes with stack errors.
const char *latArray[ptsN];
const char *lngArray[ptsN];
//  or
String      latArray[ptsN];
String      lngArray[ptsN];
//  or
double      latArray[ptsN];
double      lngArray[ptsN];

while( myFile.available() ) {
  lineN++;
  String  latGet = myFile.readStringUntil(',');
  double dLat = StrngToDouble( latGet );
  if( dLat < minLat )  minLat = dLat;
  if( dLat > maxLat )  maxLat = dLat;

  latArray[lineN] = latGet;         //  put in String array
  //  or
  latArray[lineN] = latGet.c_str(); //  put in const char * array
  //  or
  latArray[lineN] = dLat;           //  put in double array

  String  lngGet = myFile.readStringUntil(',');
  double dLng = StrngToDouble( lngGet );
  if( dLng < minLng )  minLng = dLng;
  if( dLng > maxLng )  maxLng = dLng;

  lngArray[lineN] = lngGet;         //  put in String array
  //  or
  lngArray[lineN] = lngGet.c_str(); //  put in const char * array
  //  or
  lngArray[lineN] = dLng;           //  put in double array

  String  tmp = myFile.readStringUntil('\n');
}

where
double StrngToDouble( String dblString ) {
  double temp = strtod( dblString.c_str(), NULL );
  return temp;
}

This can compile and work - EXCEPT for reading the arrays and calculating using the floats, no matter what type of arrays I try using.  It just crashes.  What's the best way to resolve this?
Thanks, Rick

You may be out of memory. What Arduino are you using? How large is lineN? How much RAM is statically allocated (the compiler tells you that)?

I'm actually using a Wemos ESP32.  The compiler says:   Sketch uses 285032 bytes (27%) of program storage space. Maximum is 1044464 bytes.
Global variables use 37092 bytes (45%) of dynamic memory, leaving 44828 bytes for local variables. Maximum is 81920 bytes.

And lineN?...

Simplify your program. Read the data and print out what you get. Don't do anything with arrays yet. Once you have it reading and converting fine you can look at creating the arrays and adding the data to them.  To me it sounds like you may be having a buffer overrun. Too many entries being put into your arrays.

And to back that up - the first thing you do in your loop is lineN++, so you start with slice 1 instead of slice 0. Do you then go to fill slice ptsN? That's one more slice than you have...

About the size of lineN: 20 minutes * 1/sec = 1200 points.  Pretty big.  Maybe I should just keep reading the file.

Thanks, @Majenko, for pointing out that I was starting at 1, instead of 0.

The answer to this question is helpful:  https://arduino.stackexchange.com/questions/48935/put-integer-and-double-into-char-array

If lineN ever gets bigger that ptsN-1 then you will crash.  What is ptsN?


text:
SdFat initialization blocks HC-SR04
I appreciate the help of this forum very much and it`s my first time to ask you experts befor driving crazy...
ArduinoUno and SDcard-BreakOutboard and DistanceSensor HC-SR04 are not working well together. The problem - as far as I found out - is in this statement:
if (!sd.begin(sdChipSelect) || !file.open("DATALOG.TXT", O_CREAT | O_WRITE | O_APPEND)) {
// Replace this with something for your app.
Serial.println(F("SD problem"));
//while(1);
}

When it is erased the distance sensor works perfectly, if it is in place it shows 0 cm (and that for days! ;-) ). I read something that SdFat ist doing something with Pin10 but also putting it on OUTPUT - HIGH or LOW didn't do the trick. Any ideas?
Kind regards
Rob
The "minimal" code:
/*
SD card datalogger

This example shows how to log data
to an SD card using the SdFat library.

The circuit:
* analog sensors on analog ins 0, 1, and 2
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 7 (for MKRZero SD: SDCARD_SS_PIN)
*/
#include <SdFat.h>
const uint8_t sdChipSelect = 7;
// SD file system.
SdFat sd;
// Log file.
SdFile file;

// Hook up HC-SR04 with Trig to Arduino Pin 9, Echo to Arduino pin 10
// Maximum Distance is 400 cm
unsigned long echo = 10;
int ultraSoundSignal = 9; // Ultrasound signal pin
unsigned long ultrasoundValue = 0;

void setup() {
// Serial Port
Serial.begin(9600);
// Pin 9 = TriggerPin
pinMode(ultraSoundSignal,OUTPUT);

// Initialize the SD and create or open the data file for append.
if (!sd.begin(sdChipSelect) || !file.open("DATALOG.TXT", O_CREAT | O_WRITE | O_APPEND)) {
// Replace this with somthing for your app.
Serial.println(F("SD problem"));
//while(1);
}
Serial.println("card initialized.");
delay(1000);
}

void loop() {
Serial.println("Beginn");
// Distanzmessung mit HC-SR04
int x = 0;
x = ping();
Serial.print(x); Serial.println(" cm");
delay(1000); //delay 1/4 seconds.
}

unsigned long ping()
{
  pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output
  digitalWrite(ultraSoundSignal, LOW); // Send low pulse
  delayMicroseconds(2); // Wait for 2 microseconds
  digitalWrite(ultraSoundSignal, HIGH); // Send high pulse
  delayMicroseconds(5); // Wait for 5 microseconds
  digitalWrite(ultraSoundSignal, LOW); // Holdoff
  pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input
  digitalWrite(ultraSoundSignal, HIGH); // Turn on pullup resistor
  // please note that pulseIn has a 1sec timeout, which may
  // not be desirable. Depending on your sensor specs, you
  // can likely bound the time like this -- marcmerlin
  // echo = pulseIn(ultraSoundSignal, HIGH, 38000)
  echo = pulseIn(ultraSoundSignal, HIGH,38000); //Listen for echo
  ultrasoundValue = (echo / 58.138);// * .39; //convert to CM then to         inches
  return ultrasoundValue;
}

What board are you using?

Arduino Uno ATmega328P-PU (das Original!)

Pin 10 is the SS pin for SPI. Since you are using SPI for the SD card pin 10 must be an output (for SPI to operate in master mode). Ideally you will use that pin as the SS (or CS, whatever you want to call it) for the SD card.
You can't use it as the echo input of an ultrasound range finder and use SPI.

Thanks for your quick answer. I tried as you told me and switched SS/CS to pin10 and tried the HC-SR04 on pins 8/9 and 6/7 without success. Now it doesn`t work at all. Not with nor without the line.

WORKED! Sorry I had a mistake in wiring, Perfect. Thanks a lot!


text:
What's a good alternative to an Arduino Nano that can be used with Neopixels?
I'm doing an arduino project in school which requires neopixels, but the Arduino's too big. Is there an arduino I can use that's compatible with neopixels? Thanks!

How big it too big? Have you looked at Arduino Micro or Pro Mini. Even the DigiSpark runs NeoPixels

The Teensy (3.2 and better) OctoWS2811 LED Library is really interesting too.

ESP8266 mini is the best and cheaper alternative 2$5 on Ali express. Then 100% compatible with arduino toolchain/IDE + very impressive community/github library!

It's not really an Arduino, however there is an STM32 which you can program almost identical to an Arduino (using the Arduino IDE). It's the STM32F103C8T6.

There are Arduino ProMinis (they have the same specs as the nano) also there's an arduino digispark tiny 85 (they have lower specs than the nano) and at the end there are just microcontrollers that can be soldered on a PCB that is enough small for you (they have a big range of specs)
Here is a comparison to the nano


text:
Measuring lenght of time light levels peak using photoresistor
I'm trying to measure shutter speeds on old cameras. This essentially consists of:

Shining a torch at one end of the camera
putting the photoresistor at the other end
trigger the shutter which temporarily lets in the light from the torch (boosting the photoresistor values temporarily)
Recording the duration of the increased spike in light levels

What I have currently records light levels but the variation is massive and typically incorrect in that they change depending on how close the torch is to the shutter and typically records values between 400 and 900 ms which is far too long (should be about 50ms).
This is the key code I have so far:
if (shutterbot.opened())
{
    /* Measure length of time it is opened until closure */
    unsigned long previousMillis = millis();

    while(true)
    {
        unsigned long currentMillis = millis();
        unsigned long time_elapsed = currentMillis - previousMillis;

        if (shutterbot.closed())
        {
            finished = true;
            /* Report back to user */
            Serial.println("Shutter speed is: ");
            Serial.println(time_elapsed);
            break;
        }
    }

}
The open and close methods in the shutterbot class are:
/* If light is 10% higher, set it to start recording */
int Shutterbot::opened()
{
    if (light_level() > 400)
    {
    return true;
    }
    else
    {
    return false;
    }
}

/*
  If light drops to below 10% higher, set it to stop
  recording
 */
 int Shutterbot::closed()
 {
     if (light_level() < 400)
     {
     return true;
     }
     else
     {
     return false;
     }
}

The full project code is here and just needs a photoresistor module and an arduino uno to test. I'm not sure I've provided enough information so if there are any questions, please let me know. Any help is greatly appreciated and thanks for reading.

Have you tested the reaction time for the photoresistor?  Perhaps by turning on a light with the arduino and timing how fast the photoresistor hits your threshold.

if @craig is right and the photo-resistor takes too long to transition, maybe you should use a fast photo-transistor?

Thanks guys, I haven't timed the span between resting levels and the spike but I'm going to try the IR route instead. Not sure about a fast photo resistor. Do they have sampling rates or anything associated?

It is unlikely a photo resistor can be used to time an event with sub second granularity.  This is because the electrons in such a device have many conductive states which they migrate into when exposed to light and out of when left in the dark.  It takes time for the electrons to drift into and out of these conductive bands.  In some cases it may take a good portion of a second. As described in the 2nd paragraph in the Design Considerations section of the above wikipedia page:

Photoresistors also exhibit a certain degree of latency between
  exposure to light and the subsequent decrease in resistance, usually
  around 10 milliseconds. The lag time when going from lit to dark
  environments is even greater, often as long as one second. This
  property makes them unsuitable for sensing rapidly flashing lights,
  but is sometimes used to smooth the response of audio signal
  compression.

Thanks for looking into it st2000. I'll scrap the idea and go down the IR route instead

You should be able to use a photo diode or transistor as suggested by others here.  In case you were wondering I blundered into this same problem years ago on a college project.


text:
Stuck in While loop when case is activated. Arduino
I have an arduino uno that controls a light using an ir remote. The sketch works fine until I pressed button c which is case 0x10EF58A7. This case reads in values and dims the light accordingly but the only problem is i can not exit the case when another button on the ir remote is pressed! what should i do!?
#include <SoftwareSerial.h>

#include <boarddefs.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>

#include <TimerOne.h>

int RECV_PIN = 13;

IRrecv irrecv(RECV_PIN);
decode_results results;
volatile int i=0;               // Variable to use as a counter
volatile boolean zero_cross=0;  // Boolean to store a "switch" to tell us if we have crossed zero
int AC_pin = 7;
int dim2 = 0;                   // led control
int dim = 128;                  // Dimming level (0-128)  0 = on, 128 = 0ff
int pas = 8;                   // step for count;

int freqStep = 65;
char incomingByte;

void setup() {
  Serial.begin(9600);
  // initialize the digital pin as an output.
  pinMode(RECV_PIN, INPUT);
  pinMode(AC_pin, OUTPUT);
  irrecv.enableIRIn(); // Start the receiver
  attachInterrupt(0, zero_cross_detect, RISING);    // Attach an Interupt to Pin 2 (interupt 0) for Zero Cross Detection
  pinMode(AC_pin, OUTPUT);
  Timer1.initialize(freqStep);                      // Initialize TimerOne library for the freq we need
  Timer1.attachInterrupt(dim_check, freqStep);
  // Use the TimerOne Library to attach an interrupt
}

void zero_cross_detect() {
  zero_cross = true;               // set the boolean to true to tell our dimming function that a zero cross has occured
  i=0;
  digitalWrite(AC_pin, LOW);
}

// Turn on the TRIAC at the appropriate time
void dim_check() {
  if(zero_cross == true) {
    if(i>=dim) {
      digitalWrite(AC_pin, HIGH);  // turn on light
      i=0;  // reset time step counter
      zero_cross=false;    // reset zero cross detection
    }
    else {
      i++;  // increment time step counter
    }
  }
}

 void translateIR() // takes action based on IR code received
{

  switch(results.value){

  case 0x10EFD827:
  //power button
   dim = 00;
    Serial.println(" full brightness ");
    break;
  case 0x10EF20DF:
  //circle button
  dim = 128;
    Serial.println("off   ");
    break;
  case 0x10EFF807:
  // button A
  dim = 95;
    Serial.println(" dim level 1   ");
    break;

   case 0x10EF7887:
   //button B
   dim = 50;
    Serial.println("dim level 2     ");
    break;

 case 0x10EF58A7:
 // button C
 {
  while ( Serial.available() > 0) {
 unsigned int num = Serial.parseInt();
 num = map(num, 0, 255, 0, 128);
 unsigned int num1 = map(num, 0, 128, 128, 0);
// num1 = constrain( num1, 0,128);
 dim = num1 ;
   Serial.print(" auto   ");
   Serial.println(dim);

   delay(800);
   Serial.flush();
    //break;
   }
  break;
}
 break;

  case 0x10EF10EF:
//button left
    {
    if (dim<127)
   {
    dim = dim + pas;
    if (dim>127)
    {
     dim=128;
    }
    }
    }
    Serial.print(" dimming ammount=   " );
    Serial.println(dim);
    break;

  case 0x10EF807F:

  //button right
   {
      {
  if (dim>5)
  {
     dim = dim - pas;
  if (dim<0)
    {
      dim=0;  // in vechiul sketch era 1
    }
   }
   }
   }
     Serial.print(" dimming ammount=   ");
      Serial.println(dim);
    break;

   default:
    //Serial.print(" unknown button   ");
    //Serial.println(results.value, HEX);
{}
  }

}

void loop(){
  int i=0;
   if (irrecv.decode(&results)) {

   translateIR();
        irrecv.resume(); // Receive the next value

   }
     delay(700);
 }

What is sending Serial comms to you and how often is it sending?  That while loop is checking for something available from serial.  So obviously something always is.  You also seem to have an extra break after that case and I'm not sure what that is about.

Towards the end there are braces all over the place.  Often times just formatting the code will reveal logic errors that you couldn't see before.  We dont' just line all our blocks and braces up because it is pretty.

The problem is that calling Serial.parseInt() does not remove data from the buffer. So, Serial.available() will not decrease in your case, but increase with every input you give.
You will need to call Serial.read() and then convert the received bytes to a number.
@Majenko generally you're right, but it's okay to use a while loop in this situation. If there is data in the buffer, this data has to be handled. And as the arduino is not capable of multitasking it will need to take the required time, no matter if in the main loop or in a subfunction.

I've just tried it on an ESP8266 and figured out, that Serial.parseInt() does not decrease Serial.available(). As I don't think this depends on the device, but the library, I'd say that's the problem. And about the while loops: there is no way that the routine gets stuck in that special case (except one does not clear/read the buffer) and the time needed to accept data is so essential that it's just fine to do it right at that point! And I can't see a call to read() in that loop, btw...

If you wan't to respond to someone's post, comment under it and don't use your answer for that. This site isn't a discussion forum. And you can edit your own answer to add additional info. Don't put them into the comments.

And I don't know how you tested that, but Serial.parseInt() does remove bytes from the buffer. https://pastebin.com/9MSyyJ4U

@gre_gor I've commented a comment that obviously has been deleted by the author.

@gre_gor I didn't test it by reading, but by doing it. Whatever it says in your link, try it yourself. I'would be curious if it's a bug on ESP

Don't use the while loop, set a boolean when the C has been pressed.
Within the loop (main loop, not the while loop within the C key check), check if the boolean is set, and if so, check if there is serial input. If so, handle it, e.g. after or before checking all keys in the switch statement. This way alternatively keys are checked and serial input is handled.
There are good reasons not to use a while loop:

A while loop makes it impossible to do other tasks 'more or less' simultaneously.
A while loop can never end, meaning the device stops responding/functioning.
A while loop which takes too much time can affect the timing of other parts of your sketch.

IF you need a while loop, think twice, after thinking you need one, make sure it always ends within the condition or with a break

You shouldn't have while loops in your switch/case like that.
In fact, you shouldn't really have while loops at all.
Instead, your case should just set a "state" variable which tells the rest of your loop() function how to handle any serial data that arrives.


text:
Xbee shield to shield connection sends but not receives correctly
Setup:
2XArduino Uno
2x XBees S1
2x Sparkfun xbee shields.
My first arduino reads in values from a photoresistor and sends the values to the second arduino.
I know for sure the arduino is sending  values because when i plugged the second xbee directly into the computer and opened the serial monitor correct values showed up in the serial monitor. But the problem is when i attach the second Xbee onto its sparkfun shield and arduino i get repetitive wrong values .
Can someone please tell me what i am doing wrong?
I am doing this to make sure i get the right values before i beef up the project.
Sender sketch
#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
#include <XBee.h>
int photocellPin = A0;     // the cell and 10K pulldown are connected to a0

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

int photocellReading;     // the analog reading from the analog resistor divider
 SoftwareSerial XBee(2,3);
void setup(void) {

  Serial.begin(9600);
  XBee.begin(9600);
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("Wireless LightDimmer");

}
 void loop(void) {
  photocellReading = analogRead(photocellPin);
  lcd.setCursor(0, 1);
  lcd.print("Photocell= ");
  lcd.setCursor(11, 2);
  lcd.print(photocellReading);
  //Serial.println(photocellReading);
  lcd.setCursor(20, 0);
  lcd.print("Measured in lux");

  delay (500);
  lcd.setCursor(20, 3);
  lcd.print(" ");
 // Serial.print("Analog reading = ");
 // Serial.print(photocellReading);
   photocellReading = 1023 - photocellReading;
 unsigned int LEDbrightness = map(photocellReading, 0, 1023, 0, 255);
   Serial.println( LEDbrightness);
    XBee.print(LEDbrightness);

  delay(1000);
}

recieving sketch
#include <SoftwareSerial.h>
#include <XBee.h>

SoftwareSerial XBee(2,3);

void setup() {
 // Begin Serial communication
 Serial.begin(9600);
 }
void loop(){
 while ( Serial.available() > 0) {
 unsigned int num =  Serial.read();
 Serial.println(num);
 delay(2000);
 }
}

Check for Vref u r getting full (1024) ADC value.

The xbee pins can only read up about 1.2V which it will show 256 bit. You should check how much the photoresistor is giving out because it might gives something that is more than the xbee pin can handle.


text:
Analog Read dummy file
Can we use just a analog Read without storing it
i hear it it a good practice to take two reads
for better accuracy
example:
// Read extra analog inputs
    for (int i = 0; i < 8; i++)
{
    // Read analog pin to nothing.
        analogRead(i]); // analog-read is not writing to anything
}

// Read the analog inputs
for (int i = 0; i < length; i++)
{
    // Write the state of the analog pin to the response buffer.
    slave.writeRegisterToBuffer(i, analogRead(analog_pins[address + i]));
}

You only need to do that if you are changing pins between reads in free running mode.  The way you’ve done it here wouldn’t work because you change pins after your dummy read.  You’d want to read the same pin twice in a row.  But yes, you can call the function without storing the result to answer your question.

how about this ?
// Read the analog inputs
for (int i = 0; i < length; i++)
{
    analogRead(analog_pins[address + i]); // for pre read

    // Write the state of the analog pin to the response buffer.
    slave.writeRegisterToBuffer(i, analogRead(analog_pins[address + i]));
}


text:
cant find what is error on my code
im working on project which include using of motors and a float switch
im getting an error message which expected '}' at end of input .
i cant find where should i correct it, btw im putting a float switch at the first of the coding (which on top) and im getting and error, but when i remove the float switch function coding, its running well without any error. so how can i put this switch to it become functional? here is the coding;
int motorPin = 4; // pin that turns on the motor
int blinkPin = 9; // pin that turns on the LED
int lamp1 = 5;// lampu pape
int motorklorin = 3;// isi klorin
int switch1 = 2;// switch float
void setup()
{
  pinMode(motorPin, OUTPUT);
  pinMode(blinkPin, OUTPUT); // set pin 13 to an output so we can use it to turn on the LED
  pinMode(lamp1, OUTPUT);
  pinMode(motorklorin, OUTPUT); // MOTOR UNTUK ISI KLORIN
  pinMode(switch1, INPUT_PULLUP);// PELAMPONG
}

void loop()
{
if(digitalRead(switch1) == HIGH)
{
  digitalWrite(motorklorin, LOW);
}
else
{
  digitalWrite(motorklorin, HIGH);
  delay(2000);
  }
{
  digitalWrite(motorPin, HIGH); // turn on the motor
  digitalWrite(blinkPin, HIGH); // turn on the LED
  digitalWrite(lamp1, HIGH);// on lampu
  delay(2000);        // multiply by 1000 to translate seconds to milliseconds

  digitalWrite(motorPin, LOW);  // turn off the motor
  digitalWrite(blinkPin, LOW);  // turn off the LED
  digitalWrite(lamp1, HIGH);// motor 1 jalan (air start turun)
  delay(2000);        // multiply by 60000 to translate minutes to milliseconds

  digitalWrite(motorPin, HIGH); // turn on the motor (motorisi balik air jalan)
  digitalWrite(blinkPin, HIGH); // turn on the LED
  digitalWrite(lamp1, LOW);// on lampu
  delay(5000);        // multiply by 1000 to translate seconds to milliseconds

  digitalWrite(motorPin, HIGH);  // turn off the motor
  digitalWrite(blinkPin,HIGH);  // turn off the LED
  digitalWrite(lamp1, HIGH);// OFF LAMPU semua motor stop
  delay(1000);        // multiply by 60000 to translate minutes to milliseconds
  }

“expected '}' at end of input” seems quite self-explanatory to me. What do you not understand about it?

It's as simple as counting. Use your fingers if you need to, even your toes if you nest that deep.

The code above contains 5 {s and 6 }s. The numbers should match.

https://majenko.co.uk/blog/expected-end-input-error

actually i didn't know how to fix it

Add an extra line with } last and try compiling again.

There is an extra { right after your else{} statement.  Delete this and the code should compile.

Alright bro, thanks for the guide now finally i can compile the code.

If that is the case, please accept the answer.

I cover this error and how to diagnose it in a blog post.  Here it is quoted for posterity:

A common problem, and one that can cause a new programmer to pull their hair out.
However, it's a problem that always has a simple solution, and with the right tricks it's also easy to find where the problem lies.
Let's take the following little code snippet, which throws up this exact error:
byte i = 0;

void doSomething() {
  digitalWrite(3, LOW);
}

void doSomethingElse() {
  digitalWrite(13, HIGH);
}

void setup() {
  // put your setup code here, to run once:
  pinMode(13, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (i == 1) {
    doSomething();
  i++;
}

At first glance that all looks perfectly good. But you compile, and you get:
/home/matt/Arduino/ErrorTest/ErrorTest.ino: In function 'void loop()':
ErrorTest:21: error: expected '}' at end of input
 }
 ^
exit status 1
expected '}' at end of input

Line 21, of course, is the last line of the file. And the error is pretty explicit - it expects a } at the end of the file. However, there is plainly one there already. So what is it on about?
Simply put, there aren't enough } to balance out the number of { in the file. For every { there must be a } to go with it. On this little file it's easy to just go through and count them all. Add one for a { and subtract one for a }. If the answer is not 0 then there's something wrong. But it can take careful looking to see where the missing one should be, and even I have spent hours going cross-eyed trying to find the location in a big project.
There is one little trick, though, that can help you: Auto Format. The Auto Format facility in both the Arduino IDE and UECIDE (and many other IDEs as well) will sort out your indenting for you according to the presence of (amongst other things) { and }.  If the brackets don't match up the formatting would end up wrong.
So let's pass this little program through the auto formatting and see what happens:
byte i = 0;

void doSomething() {
  digitalWrite(3, LOW);
}

void doSomethingElse() {
  digitalWrite(13, HIGH);
}

void setup() {
  // put your setup code here, to run once:
  pinMode(13, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (i == 1) {
    doSomething();
    i++;
  }

As you can see the loop() function's indenting has changed. And if your eyes are sharp enough you'll already see what was wrong. The "if", which had an opening bracket, didn't have a closing one. The "i++" was supposed to be outside the "if" (as can be seen by the original indenting), but actually it wasn't, and the end of the function was really the end of the "if", leaving the function unfinished.
So fixing it is now really easy. By auto formatting we can see where the imbalance occurs, and fix it:
void loop() {
  // put your main code here, to run repeatedly:
  if (i == 1) {
    doSomething();
  }
  i++;
}

And now it compiles. But of course that little snippet doesn't actually do anything useful...

Oh okay i noticed it. thank you so much for your guide


text:
Connecting 2 arduino on same ground
I'm working project which consist of 2 arduino running a 2 different sketch, However, can i make these 2 ic to run on same power +ve and same ground?

Yes, I think you can connect both gnd and both 5v pins. Which arduino board is it? The voltage regulator might get damaged when a strong 5v is suddenly applied to the 5v pin. When using a power supply for one board, it might be safer to connect both Vin and both gnd. Always connect the grounds (gnd pins) when more than one arduino board is used in the same project.

Yes, you can. Just be sure, that you connect both Arduinos in parallel to the power source (both power inputs together to the power output of the source and both grounds together to the ground of the source), so that the current for the second Arduino won't flow through the first Arduino. Also use a power source, that is capable oft providing enough current for your needs.


text:
Preventing EMI on PCB
i've made a project consisting of 3 DC motor pumps, Atmega328p on custom PCB, and a relay. I found a problem which causes my PCB custom arduino trips over and over again caused by 12V DC MOTOR. I fix it already by putting a flyback diode on motor. it runs much better but still have a small number of trips on my arduino.

probably i've a bad PCB design and lack of components.
is there a way to prevent these electromagnetic interference caused by motor?
or some improvements on my PCB board?

Step one would be to add the missing decoupling capacitors to the MCU. Step two would be to use a proper ground pour instead of wimpy traces.

is there other way to put  the decoupling capacitors without making and design the new pcb? using this current PCB that i already make?

Use 0805 SMD capacitors and solder them between the MCU pins on the underside of the board.

Place the through-hole capacitors flat on the underside of the board. Bend the leads so they touch the solder joints of the IC(-holder). The solder them, and clip any excess lead.

Had a problem like this. I ended up using a separate power supply for my DC motor. Don't forget to connect the GND's.

do you mean to connect GND motor and arduino in the same GND? because mine was using 12V DC pump while the arduino had their own power supply.

Yes, connect a GND between both

The most critical failing of your PCB is the fact that you have no decoupling capacitors near your MCU power pins. These are absolutely required, and are not optional.
To modify your existing PCB, so you don't have to roll a new one, just solder a 0.1µF 0805 SMD capacitor between each VCC and GND pair of pins on the underside of the board.
You should also reduce both the ground impedance and the power supply impedance by replacing your ground traces with a ground pour, and fatten your power traces up a little.

i don't have SMD components over here. any alternative? a ceramic or something?

You could solder a small leaded ceramic in the same way - just be careful of shorts. Insulate the leads if you can.

can i use ceramic 22uF? as this only on my inventory for now.

Ceramic 22uF? I think you have the wrong value there. If they're the ones that you use for the crystal then you probably mean pF not uF. And no. They're too small a value. You need around 100nF (0.1uF, 100000pF). They are the single most common value of ceramic capacitor in use in digital circuits. Get some. You will need them.


text:
Burning bootloader
I'm using arduino atmega 328p and currently using on custom PCB
I programmed using the arduino board and take the IC and migrated to my custom PCB
currently the program run well on the arduino board but after i tried to run it in my custom PCB  and i found it didn't worked
im using along with 16000 mhz oscillator with 22n capacitor

as shown this is my schematic for my PCB

this is my trace for my PCB board
so is this problem caused by my schematics or i didn't upload the bootloader?

You have no decoupling capacitors. Your crystal layout is abysmal.

what do you mean by abysmal and decoupling capacitors?

By abysmal I mean: crystal is too far from the chip pins. The capacitors are poorly grounded. The traces are too angular. There is no guard ring or ground pour. If you don't know what decoupling capacitors are then you need to go and learn the basics of digital circuit design.

Did you use 22nF with the crystal?  You need 22pF.  16 MHz  = 16 x 10^6 = 16,000,000 Hz (not hz).  16000mhz is not correct, that's like 16000 x 10^-3 = 16 Hz.  M = Mega = 1 million.  m = milli = 1/1000.  u = micro = 1/1000000.

I like to give folks the benefit of the doubt, and correct when needed.  Must be the engineer/coach in me, and plenty of non-native English/American/engineer interactions.

oh okay i see, it seems I need to use the 22pF rathe than 22nF, get the crystal corrected so it would near to the chips, but what did u mean the capacitor was poorly grounded? is it means i need to make a larger ground traces for the capacitors?

You should use a ground plane, not ground traces. Reduces the impedance.

Here is a good design. The final posting - right at the bottom.

Schematic corrections:
Missing 0.1uF caps on VCC, AREF pins.
AREF pin connected to 5V - don't do that. It will connect internally using the ADC Mux if used.
C1, C6 need to be 22pF as noted earlier.
Xtal and C1, C6 should be right next to the chip as noted, with no traces going under the xtal.
Board should have Gnd plane anywhere there is not a trace.
Use Vias to connect top & bottom Gnd planes.
Do not use traces to connect all the Gnds - have pins connect to the Gnd planes instead.
Add a 1uF or 10uF electrolytic capacitor where power comes into the board, especially if the power leads will be long.

can i have a full schematic drawing include the components as u listed?

Sure,  http://arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf  This has a resonator instead of the crystal and caps, and also shows a voltage regulator.

i currently using atmega 328p ... is this usable for atmega328p instead atmega328?

328p is the standard chip used on Arduino Uno, Nano, Promini. That is what the bootloaded is set up for.  328 has different 'signature bytes' and uses a little more power.

i just looked at my custom board that i just make. i found out that the pin 20 doesnt have any trace connected anywhere. is this can be a problem that causes my arduino didn't work?

Yes! The chip needs power to work. VCC and AVCC both need to connect to 5V, both should have a 0.1uF cap connected to them also.


text:
Splitting SCL and SDA pins
For a robotics project I am using an MCP23017 I/O Port Expander in order to have more pins available, and I am also using a PS2 controller for input. Both of these require pins 4 and 5 (because these are the data and clock pins). I was wondering if I can use a breadboard to simply connect these two pins to both devices in order to provide both of them with data and clock pins.
I am using an Arduino UNO and a playstation 2 controller with the following guide:
http://www.techmonkeybusiness.com/using-a-playstation-2-controller-with-your-arduino-project.html

Nowhere in that link does it mention using the I2C pins. The PS2 uses a bitbanged custom protocol. It can use any pins. You can only use I2C pins for I2C.

You are confusing pins here. In the library you mention there is a function call to set up the gamepad:
 ps2x.config_gamepad(5,4,3,2, false, false);
 //setup pins and settings: GamePad(clock, command, attention, data, Pressures, Rumble)

That is digital pins 5, 4, 3 and 2.
I2C uses analog input pins A4 and A5 on the other side of your Uno board.

An I2C bus can be connected to many slaves at the same time, since in the I2C protocol every slave has an address.
But, as Majenko wrote in the comments, the library for the PS2 controller doesn't use I2C. The communication with the controller is bit banged, meaning that every part of the communication is done by software. This can be done with every digital pin on the Arduino. In your setup you have to usw the function ps2x.config_gamepad().  In it's parameters you can set the pins that the library will use.


text:
Why was the Atmega16U2 used on the Arduino UNO as a USB to Serial converter?
This is the first time that I realized that extra SMD IC near the USB port of the Arduino UNO is actually a fully fledged microcontroller, I thought that it was just a USB to Serial converter. Further research into this chip left me with more questions than answers.
First of all, why did Arduino decide to use the Atmega16U2 as a USB to Serial converter? Couldn't they have gone with an FTDI chip instead? I came across this phrase on Quora "The best part is that you can also program and create your own applications on the 16u2 if you have an In-circuit Serial Programmer". How exactly does this work?
What about the two other set of connectors on the board? (other than the two main rows of headers) The ones labeled ICSP and JP2? Is the JP2 for the 16U2? I read that these could be used for burning the code onto the Atmega328P so that it can be modified, but not overwritten. What are any other uses for the 16U2 on the Arduino UNO?

FTDI is more expensive than the 16U2 AFAIK. Examples of reprogramming it are: to use it as a USB MIDI device or HID.

There is a separate ISP/ICSP header for it. Then use something like an Arduino as ISP, Atmel ICE, etc (I have no time now, but I might bbe able to write an answer and post photos soon)

First reason I'd guess is price:

FT232 on octopart: USD2.65 ~ 3
Atmega16U2 on octopart: USD2.12 ~ 2.2

They can probably get much better deals considering that the Atmega328 is also from Atmel (now Microchip).
About the programming:
There are some projects which make the Atmega16U2 into a MIDI device over USB or HID, for example some repos: 1, 2, 3. I've used the second one I think, and it works fine.
You can program it with an ISP/ICSP programmer such as Atmel ICE(below) or Arduino ISP.

Use the ISP pins by the Atmega16U2:

@duskwuff -- True, it could have been the other way around!


text:
What do I have to change to make this code functional?
I have a joystick, an I2C 16x2 character display, and an Arduino. I want to move the joystick and get an on-screen character (specifically, the letter h) to move in the direction that I pushed the joystick. Here is the Arduino code.
#include <LiquidCrystal_I2C.h>
int xVal;
LiquidCrystal_I2C lcd(0x27, 16, 2);
int yVal;

int blockPos[]= {8, 0};
int blockPosBack[]= {8, 0};

int ycal;
int xcal;
void setup() {

    lcd.begin();
    lcd.clear();
    lcd.backlight();
Serial.begin(9600);

pinMode(A0, INPUT);

pinMode(A2, INPUT);
lcd.setCursor(blockPos[0], blockPos[1]);
//lcd.print("h");

ycal = 500;
xcal = 514;
}

void loop() {

xVal = analogRead(A0);

yVal = analogRead(A2);

Serial.print(" Y is...");

Serial.print(yVal);

Serial.print(" X is...");

Serial.println(xVal);

blockPosBack[0] = blockPos[0];
blockPosBack[1] = blockPos[1];

if(xVal < (xcal - 150)){
  if(blockPos[0] > 0){
    blockPos[0] - 1;
    }
  }

  if(xVal > (xcal + 150)){
  if(blockPos[0] < 15){
    blockPos[0] + 1;
    }
  }

  if(yVal < (ycal - 150)){
  if(blockPos[1] > 0){
    blockPos[1] -1;
    }
  }

  if(yVal > (ycal + 150)){
  if(blockPos[1] < 1){
    blockPos[0] +1;
    }
  }
if(((blockPosBack[0]) != (blockPos[0])) && ((blockPosBack[1]) != (blockPos[1])){
  lcd.clear();}
  lcd.setCursor(blockPos[0], blockPos[1]);
  lcd.print("h");
}

The problem is, I get a message saying that "expected ')' before '!' token". How do I solve this, and how do I change the code to make it functional?
Edit: I learnt that '!' is not the same as 'not equal to', which is '!='. I tried this, but now the h just sits at the initial position but doesn't move when I move the joystick. What do I have to change in the code to make it work?

if(blockPos[1] < 1){blockPos[0] +1;} - shouldn't that be blockPos[1] +1 ?

Like stated in my comment, to have proper condition for clearing the display, the condition you should want to meet are:
if ( (newX != previousX) OR (newY != previousY)) {
    clearLCD()
}
EDIT: Or else, what you're saying is that you're only clearing the display when you have changed both X and Y at the same time
And to adress your problem with the 'h' not moving, you need to change the lines
blockPos[0] - 1; etc
into
blockPos[0] = blockPos[0] -1;
or
blockPos[0]--;
or else, you're not really assigning the new value to the variable containing the position to use in the display.

First of all you should have edited the code way better, if you want help and want us to understand you must edit it properly.
if(((blockPosBack[0]) != (blockPos[0])) && ((blockPosBack[1]) != (blockPos[1])){
  lcd.clear();}
  lcd.setCursor(blockPos[0], blockPos[1]);
  lcd.print("h");
}

I took some time to understand that lcd.setCursor and lcd.print wansn't part of the if. When you are using 2 different sensors or components, you must try them separatly first, and when you got them both working fine that's when you use them together.
https://www.arduino.cc/en/Tutorial/JoyStick
This is an example pretty much more simple than yours, so i just think you must try lcd first, and when you understand how lcd works, and how joystick works, you can easly interact them.

just saying it was a bad edit, it wasnt critical in this code because it was short, but in real big codes this edit is critical. And im refering to another example because it was way simple, you didn't understand my aswer, i "advised" for future codes

Yeah I did, but you didn't understand my comment. Imo, advise for the future is not an answer to a question, but belongs in a comment, or as an addendum to a proper answer to the OPs question. Remember that these questions should be useful to anyone else reading the Q/A as well.


text:
Stop Buzzer after some seconds/time?
This is a "water level alarm/display" sketch using and Arduino and ultrasonic sensor.
The buzzer gets on when the water level hits 100% or more.
But most of the time the water level will stay @ 100%, and I dont want the buzzer to run for long time.
How can I set the buzzer to make sound only for 15 seconds ?
It should turn off after 15 seconds, even if the water level is @ 100%
#define trigPin 8
#define echoPin 9
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int BUZZER = 10 ;

void setup(){
      int duration,distance,percentage,heightTank;
      Serial.begin (9600);
      pinMode(trigPin,OUTPUT);
      pinMode(echoPin,INPUT);
      lcd.begin(16,2);
      lcd.print("HELLO");
        pinMode(BUZZER,OUTPUT);
}

void loop(){
      int duration,distance,percentage,heightTank,deviation;
      //You'll probably want to change the next 2 lines.
      // The first one is the max. level of the water.
      // The next one is how high the sensor is above that max. level.
      heightTank=65;
      deviation=4;

      digitalWrite(trigPin,HIGH);
      delayMicroseconds(1000);
      digitalWrite(trigPin,LOW);
      duration=pulseIn(echoPin,HIGH);
      distance=(duration/2)/29.1;
      percentage=100-(((distance-deviation)*100)/heightTank);
      Serial.println(distance);
      Serial.println(percentage);
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Current tank");
      //lcd.print(distance);
      //lcd.print(" cm");
      lcd.setCursor(0,1);
      lcd.print("level: ");
      lcd.print(percentage);
      lcd.print(" %");
      delay(1000);

      digitalWrite(BUZZER,HIGH);
  if (percentage > 99) {digitalWrite(BUZZER,HIGH); delay(100); digitalWrite(BUZZER,LOW); delay(100);}
  else  {digitalWrite(BUZZER,LOW);}
  }

For this you will have to implement a finite state machine. This is a
very common paradigm in the embedded world. I recommend you start by
studying this tutorial: The Finite State Machine, by Majenko.
Four your particular problem, I would implement a machine with three
states: IDLE, ARMED and ALARM, the ALARM state being the only one in
which the buzzer is on. The transitions would be:

ARMED → ALARM when the level hits 100%
ALARM → IDLE after 15 seconds spent in the ALARM state
IDLE → ARMED when the level gets below 90%

Note that the only difference between IDLE and ARMED is that the IDLE
state will not go into ALARM when the level reads 100%, as you have to
go through the ARMED state before. The threshold at 90% percent is meant
to add some hysteresis. You can tweak the threshold value to your
taste.
I leave the implementation to you. It should be easy one you have
studied Majenko's tutorial.

Edit: Just to illustrate the generality of the concept, I would like
to point out that the code in Look Alterno's answer can be thought of as
a finite state machine where the state is implicitly encoded into the
variables lastBuzzer and percentage. The implicit state is:

ARMED when lastBuzzer == 0
ALARM when percentage > 99 && millis() - lastBuzzer < 15000L
IDLE when  percentage > 99 && millis() - lastBuzzer >= 15000L

The line lastBuzzer = 0 establishes the ARMED state as soon as
percentage ≤ 99. Note that this lacks hysteresis: if the reading
fluctuates between 99% and 100%, the alarm will sound again and again.
I personally prefer using an explicit state variable, as it makes the
code clearer to me. But then, the best approach is whichever makes the
code clearer to you.


text:
Serial monitor in Arduino IDE for RobotDyn ESP8266-Pro via CP2102
I bought a couple of "ESP8266-Pro" micro-controllers from a Chinese company named RobotDyn.  There's no real documentation with them, but I've bought a lot of other stuff from them in the past that worked out really well, so I took a chance.
After some work, I am finally able to program the board with the Arduino IDE 1.8.1.
The problem is that I am unable to get the serial monitor working to see what's going on with the code.
What do I need to do to get this to work, or is it simply not possible?  In order to program the board, I need to connect EN to VIN, and both IO0 and IO15 to GND.  I assume I have to disconnect that to actually run the board after programming, but I don't know and haven't gotten anything to work yet.
Here's a photo of the board hooked up for programming.  What do I need to do to restart it with the serial monitor working?

scroll down https://robotdyn.com/catalog/boards/wifi_module_esp8266_pro_8m_flash/

I've seen those before. First place I looked. But none of them answer my question in a way I understand, at least. If one of those three docs explain how to connect serially, I'd appreciate it if you explained, more specifically, what I'm not grokking.

You applied connections like it was a plain esp8266. The board has the necessary pull-ups and pull-downs. Connect it at first only to GND, VCC, TX, RX. The button pulls gpio0 LOW to enter flashing mode at power up.

I'll try just those 4 pins, thanks. But I'm pretty sure I started with that and got nowhere. I'll respond with results later.

As I thought, I had tried this.  Does not work as you expected.  I consistently get the following errors from the IDE when it attempts uploading:
warning: espcomm_sync failed, error: espcomm_open failed, error: espcomm_upload_mem failed, error: espcomm_upload_mem failed. As I say here (https://stackoverflow.com/a/47742473/1480995), I am unable to program unless IO15 and IO0 are grounded and EN is run to VIN, regardless of the use of the button.

So it seems that the trick to being able to monitor serial output on the RobotDyn ESP8266-Pro is to NOT have DTR and CTS from the CP2102 programmer connected to the board's RST and IO12 pins.
With only the four remaining lines connected (VCC, GND, TXO, and RXI), you will see normal serial output on the the Arduino IDE's serial monitor after uploading firmware completes.
This works for me with the board set as "Generic ESP8266 Module" or as "NodeMCU 1.0 (ESP-12E Module)".
This still doesn't get you serial monitoring when you just plug in the device, though.  It only works after firmware has been uploaded.  Still working on that.

without DTR signal the Serial Monitor doesn't restart the board as you know it from Arduino

OK, I'll look into that.  I'm not familiar with these serial devices at all - everything I've used had built-in USB except from an Arduino Pro-Min that worked with the programmer cable I got with my CP2102 out of the box.


text:
Wake up ESP8266 from deepSleep with a button
I have a button with two isolated tracks. I want to be able to wake up esp from deepSleep with this button, and also detect that it was clicked. So i can't connect it to reset, because esp won't work if i don't release a button. And if it's not at deepSleep, it will reset, and i don't want it. How to do this?

Can you post code that you have so far?  Also, what do you mean by "two isolated tracks"?

Connect the button, with a pull-up to a GPIO. Also connect the button via a small capacitor to the reset pin. The arduino boards use the same trick to reset the ATMega328 via the USB to serial chips DTR-pin.

I don't have any code that would relate to this functionality yet. By "two isolated tracks" i mean that this button has 4 pins, and 2 paths are isolated, so you can connect two separate things to same button. One path will wake up ESP, and second will be connected to one of GPIOs.  Will thing with capacitor also reset it when it's running? I want it only to reset once at sleep, and don't do it while working.

Could you please draw me it in paint or something?

Possible duplicate of Deep Sleep Reset with Shock Sensor

You can't stop deepSleep, all you can do is reset the board so connect the button to the reset pin and make the appropiate set-up:

Connect a pullup resistor (10k) in RST
Connect the button from RST
to GND

When you push, RST has GND so the ESP gets reseted.
Remember that deepsleep only works for about an hour so you have to contemplate this situation, too, maybe with a static variable...
EDIT Thanks Juraj for the comment: "from SDK API "system_deep_sleep(0): there is no wakeup timer; in order to wake up, connect a GPIO to pin RST; the chip will wake up by a falling-edge on pin RST."

from SDK API "system_deep_sleep(0): there is no wakeup timer; in order to wake up, connect a GPIO to pin RST; the chip will wake up by a falling-edge on pin RST."

the reference assumes the esp8266 is used as 'coprocessor' for a main MCU, because it wasn't designed to be used standalone. so the mentioned GPIO pin is a pin of the main MCU


text:
Arduino and AVR Serial Communication over USB
I have a Arduino Uno Rev3 and I would like to use a AVR development toolchain to write a program that performs serial communication over USB.
Doing this using the Arduino IDE is fairly simple:
void setup() {
   Serial.begin(9600);
}

void loop() {
   int i;
   while(1) {
      Serial.write("hello\n");
      delay(5000);
   }
}

Then from Linux, I can simply read from /dev/ttyACM0 and every 5 seconds I get "hello\n".
I found a blog post titled Simple Serial Communications With AVR libc that explains how to perform serial communication using an AVR development toolchain. The simplified version of the above Arduino sketch is below.
#ifndef F_CPU
#define F_CPU 8000000UL
#endif

#ifndef BAUD
#define BAUD 9600
#endif

#include <stdio.h>
#include <avr/io.h>
#include <util/delay.h>
#include <util/setbaud.h>

void uart_init() {
    // Upper and lower bytes of the calculated prescaler value for baud.
    UBRR0H = UBRRH_VALUE;
    UBRR0L = UBRRL_VALUE;

    // Configure data frame size to 8-bits.
    UCSR0C = _BV(UCSZ01) | _BV(UCSZ00);

    // Configure to enable transmitter.
    UCSR0B = _BV(TXEN0);
}

void uart_putchar(char c) {
    // Wait until the register to write to is free.
    loop_until_bit_is_set(UCSR0A, UDRE0);

    // Write the byte to the register.
    UDR0 = c;
}

void uart_putstr(char *data) {
    // Loop until end of string writing char by char.
    while(*data){
      uart_putchar(*data++);
    }
}

int main() {
    uart_init();

    while(1) {
        uart_putstr("hello\n");
        _delay_ms(5000);
    }

    return 0;
}

The problem is, this doesn't actually work. I can build and flash the ATmega328p but reads to /dev/ttyACM0 block forever. I suspect what is happening is that the serial communication is occurring on some pins and not over USB, but I am not sure.
Anyone have any idea on how I can emulate Serial.write using an AVR development toolchain and have the output be written over USB?

8000000UL my Uno board has a standard 16MHz crystal on it. Besides, what program / command do you use for reading out data over dev/ttyACM0?

I tried 16000000UL as well, still didn't work. I originally switched to 8000000UL because the on-board LED did not blink correctly with 16000000UL.

As for reading /dev/ttyACM0, I've written a simple program using the following library: http://github.com/pkg/term. However, I imagine cat or tail -f would show the same results.

Why is this being closed as off-topic? The help centre tells that questions about other IDEs, clones/counterfeits/derivatives, and other coding languages for Arduino are OK.

Turns out the problem was with my Makefile. avr-gcc was missing the -mmcu=atmega328p flag. Once I added that and changed F_CPU to 16000000UL everything works.


text:
Unused lines of code causing program to crash
I have a project which essentially involves WiFi, a web server, and an LED. I'm using the Inbuilt LED on my ESP8266 for testing at the moment. I am using the Arduino IDE for programming.
I had a problem where my code would crash after connecting to WiFi. By commenting out functions in my loop, I narrowed down the crash problem to my function that handles the LED. Here I ran into a problem, commenting out each block of code individually, and even a few at once, I wasn't able to prevent the crash. There must be more than one line causing the crash. Commenting out the entire function was the only thing that worked.
After hours of troubleshooting, I was left at the stage where I had the contents of all the if statements and loops and such commented out.
Here is what left me utterly confused. Here is the if statement:
if(webSocketActive){
    Serial.println("websocket is active, setting brightness");
    analogWrite(LED_BUILTIN, 1024 - lightBrightnessAdjust);
} else {
    //other stuff with more if-statements that are empty
}

At this point, if I comment out the analogWrite line, the program works fine. But if I leave it like this, it crashes after connecting to WiFi. (I didn't post my entire program because it is over 1000 lines long).
The baffling part about all this is, webSocketActive is never set to true prior to this point in the code... The Serial.println() never does anything, meaning the ESP definitely doesn't execute the instructions inside the if statement. But, for some inexplicable reason, simply having the analogWrite() uncommented crashes the program, even if it never executes that line.
I've also had other issues where putting some sort of Serial.print() function in the loop to repeatedly run somehow doesn't make the code crash. Could someone let me know what is going on?

Sounds like you could have some form of buffer overflow or variable alignment issue, and adding / removing code randomly changes allocations of variables or constants. You should turn on debugging and see what the crash actually is.

@Majenko So, I turned on debugging for WIFI+CORE and some other stuff. When my first test worked, I uncommented everything else in the function. It works. Why? What change does turning on debugging make?

It basically adds a load of serial prints... so it does something similar to your program changes. With debugging off and it crashing do you get an exception code on serial?

Yes I do, it's a hardware watchdog reset, so no stack dump. rst cause:4, boot mode:(3,6), wdt reset. The thing is, as I pointed out in my post, when I added a Serial print into my loop (or just into my function, which is in the loop) the program wouldn't crash. Why would this happen?

It's impossible to say.

@Majenko is there any effect Serial.print() would have on the program at all?

Well, yes. It would change the internal layout of the code. Instructions will move locations. Constant data structures will be in different places. Lots of things could change.

You put identical comments at the answers telling that you solved the issue. Please make this an answer and mark it so that we all know that your problem is solved, and how. It will help others with a similar problem.

Turns out that the MDNS.begin() in setup and the MDNS.update() in the loop was, presumable, causing some sort of undefined behaviour, since the code didn't always crash. I commented out these two lines, and the code works fine now, minus the MDNS.

Overwriting an array could clobber that functions return address.
Allocating from the heap, enough memory for the up-growing heap and the down-growing stack to collide, could cause or create the conditions for clobbering function-local data, function return-return address, or heap data, including the heap meta-data required to de-allocate that heap-block.
Writing through an uninitialized or overwritten pointer can cause about any memory corruption you can imagine; and the result can be data dependent and/or data-memory map dependent, and quite possibly non-repeatable.
Clobbering the interrupt vector of an enabled interrupt can cause improperly jumping into any part of your code, and is quite likely to be unrepeatable.

There's too much we don't know about the unseen rest of your code to do much more than speculate on possible points-of-failure.

Turns out that my code wasn't the issue. The MDNS.update() I had in the loop was what was causing the code to crash. Commenting that out fixed the issue.

I think I might know the problem (maybe you've fixed it after two weeks) but your analogWrite(Pin, Val)might end up being out of range, remember that analogWrite only takes an int of 0 to 255 therefore if your lightBrightnessAdjust variable is lower than 769 then we will get an int above the accepted input range of analogWrite().
I know the code never actually runs but it still compiles and maybe Arduino doesn't like even a possible error.
Maybe I didn't explain it very well but here's the Arduino documentation for it.
Another possible solution could be perhaps you could try defining int amount = 1024-lightBrightnessAdjust; variable beforehand and then entering the variable into analogRead because it could be fussy about doing math inside the function params (just a thought)

Turns out that my code wasn't the issue. The MDNS.update() in the loop was what was causing the code to crash. Commenting that out fixed the issue.


text:
How do I properly use the WiFi capabilities of ESP8266?
I am creating a project with an ESP8266 (Arduino IDE) which requires it to serve a webpage to a client. The module will be connected to a WiFi network by default, but when that WiFi network is not available, I need it to turn on its Soft Access Point, so that the user can still access that webpage by connecting to the AP. When the WiFi network becomes available, I want the module to reconnect to the WiFi network and disable the SoftAP.
Here is the chunk of code in my sketch that deals with all the WiFi stuff:
void wifi() {
  if(WiFi.status() != WL_CONNECTED){
    WiFi.mode(WIFI_AP_STA);

    if((unsigned long)(millis() - waitUntil) >= interval){            //this section I used as an alternative to the delay() function, the delay is 3 sec
      WiFi.begin(ssid, password);
      waitUntil = waitUntil + interval;

      if(WiFi.status() == WL_CONNECTED){
        Serial.println("Connection successful! ");
        Serial.print("IP: ");
        Serial.print(WiFi.localIP());
        WiFi.softAPdisconnect(true);
      }
    }
  }

  if(WiFi.status() != WL_CONNECTED && softAPEnabled == false){
    Serial.println("WiFi not connected, enabling SoftAP...");

    WiFi.softAP(softAP_ssid, softAP_password);

    softAPEnabled = true;

    Serial.println("SoftAP ON");
  }
  else if(WiFi.status() == WL_CONNECTED && softAPEnabled == true){
    WiFi.softAPdisconnect(true);
    softAPEnabled = false;
    Serial.println("SoftAP OFF");
  }
}

Here are the problems:

The webpage works fine when the module is connected to WiFi and I go to the IP address from a browser, but when SoftAP mode is enabled, and I connect to the AP and go to 192.168.1.1, it does not work. The next problem may be related to this.
I don't think I'm using WiFi.mode() correctly. I currently have it set to WIFI_AP_STA, but after problem 1 occurred, I tried to change it to WIFI_AP and WIFI_STA individually as I needed each mode, but this still did not work.

192.168.0.1 and 192.168.1.1 are commonly used by commercial routers as their own local address. Could your chosen station-address be colliding with that?

the default SoftAP IP with Arduino core is not 192.168.1.1. Use WiFi.softAPIP(); to print the IP

@Juraj Thanks for this. I will have a look.

@Juraj Also, I have spent way too much time searching for functions of WiFi.h. Do you happen to have a link to a website with the list of all the functions of WiFi.h?

https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/soft-access-point-class.html

https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/ESP8266WiFiAP.h

The following may not solve of your problems, but just in case it helps...
I was using the ESP8266 both in Station mode and AP. Both worked.
In AP mode, it worked but the ESP8266 ignored my instructions to set name and password for the AP , until I realised the following
. The password must at least be 8 characters long, otherwise the instruction is ignored
. in the IDE, you should erase flash AND WiFI settings, otherwise it will be "lazy" and use previous settings