text:
Arduino Code 'Bug'
I'm sharing my code.. The problem I am facing is that the code performs all the functions that are to be called except showing the MAX30100 (for heart rate) readings. I have tried this code using statement switches,cases, if-else but couldn't figure out.  Can anyone help me out regarding this?
    unsigned long runGSR() {

total = total - readings[index];         // subtract the last reading:

 readings[index] = analogRead(inputPin);  // read from the sensor:

  delay(100);

  total = total + readings[index];       // add the reading to the total:

  index = index + 1;                     // advance to the next position in the

array:

  if (index >= numReadings)               //when the end of the array is reached

    index = 0;                           // wrapped around to the beginning:

  average = total / numReadings;           // calculate the average:

  return average;       // send it to the computer as ASCII digits

    }
    void ambtemp()

    {

       reading = analogRead(A2);       //takes the reading from analogue pin 2

  tempVolts = reading * 5.0 / 1024.0;   //converts the readings to volts

  ambitemp = tempVolts / 0.01;        //output voltage /10 millivolts = 1 degree
C

  Serial.print(",Ambient Temp:");      //prints ambient temperature in serial monitor

  Serial.println(ambitemp);

  delay(10);

    }

    void hbt()    //Function for heart rate (MAX30100) in which I am having problem
    {
        do
        {
            pox.update(); // Make sure to call update as fast as possible
            if (millis() - tsLastReport > REPORTING_PERIOD_MS) {   //the loop repeats every second
            lcd.clear();
            Serial.print("HR:");
            Serial.println(pox.getHeartRate()); //prints Heart rate on LCD
            delay(100);
            ambtemp();    //calls the ambient temperature function
            gsr = runGSR();   //calls the GSR sensor function
            delay(100);
            tsLastReport = millis();
        }

You have two missing } Add them then use ctrl+t in ArduinoIDE to automatically format your code and then paste it again please. (Please use "code" function of the stackexchange editor to add code as code)

I try it but it doesn't work.

Any other solution... there is some kind of bug that is not plotting the readings of MAX30100

What I meant was "Show us your complete code in a way that we can run it on our Arduino simulators" Right now the code you pasted in the question does not compile. No one can help you right now. (You can Edit the question and change the code to the complete one)

Serial.println(pox.getHeartRate()); //prints Heart rate on LCD .... the comment does not match the command

When you say "I try it but it doesn't work" we understand the result but it isn't enough for us to help you.  For example, do you get partial output? If you try lcd.print("HR:"); do you see that on the LCD? If not, then your hbt() function is never being called because there is no branching inside the function to keep that link from executing. We can't see enough of your code you be any more assistance.  Where did you get the sample you are using, what libraries are you importing, etc. Also, it looks like that 'DO' block has no WHILE / UNTIL  visible, is it an infinite loop?

I see the result "HR:" printed on lcd but it doesn't print the value of the sensor that should be 60-100 bpm. I have mentioned the main part of code and have already included required library needed for the code. What kind of error it can be that calls hbt function but does print its value?

I assume you use this as source for your code:
This means that:
#include "MAX30100_PulseOximeter.h"
PulseOximeter pox;

Your issue is that the line:
Serial.println(pox.getHeartRate()); //prints Heart rate on LCD

Does not actually print anything on the LCD.
It only shows the value on the serial.
Try using lcd.print()

No, its  neither print value on lcd nor on serial ide.

Paste your entire code in the question please.

Done. check now please

There are many many errors in your code. According to StackExchange rules you should provide a Minimal, Complete, and Verifiable example https://stackoverflow.com/help/mcve that allows other people check for solution to your problem. Your example still does not compile and I can't test it.


text:
Arduino compatible's serial port not showing Mac OSX
I bought an Arduino-compatible Freaduino board atmega8 (I selected the board type as Arduino ng or older atmega8). I installed the Arduino IDE on Mac OS X and the FTDI drivers. But my serial port looks like this when I connect the board:

And when I try to upload the program, this is the error I get:

Can someone tell me what is the mistake? I am clueless.
UPDATE: the problem was I had not installed the driver properly (I guess). I uninstalled and reinstalled them and it worked perfectly. Also made a YouTube tutorial regarding the same. http://youtu.be/BwatajQO_88

Have you set the Board correctly to the one you have?  Also, almost definitely it is not the Bluetooth tty that you have connected to.  Very likely it is the USB tty.

yes the led (PWR) glows on the board as soon as i connect it.

i tried tty.SLAB_USBtoUART to. it dint work same error

Disconnect the board, close the IDE, and re-open it.  Did any of the devices disappear?  Also (with it plugged in) do apple-menu about - more info - system report and look at what is listed under USB.  Finally consider trying it on a different computer/OS to rule out problems with the board.  Oh, and try a different cable/USB port.  Try connecting it directly to the MAC and try connecting it through a keyboard or other hub.

Why not copy the plain text instead of uploading the lower 372kB image? Search engines won't be able to index the text and mobile users are hit with a large download where 1kB of text would suffice.

does the dmesg command show any fresh output after plugging in the Arduino?

@ChrisStratton `CP2102 USB to UART Bridge Controller:
Product ID: 0xea60
Vendor ID: 0x10c4  (Silicon Laboratories, Inc.)
Version:  1.00
Serial Number: 0001
Speed: Up to 12 Mb/sec
Manufacturer: Silicon Labs
Location ID: 0x14100000 / 8
Current Available (mA): 500
Current Required (mA): 100
` this is what comes in USB in more info about this mac. it is directly connected to mac. still same error.

@jippie i ran sudo dmesg on terminal and yes it did show changes in the output after plugging in the arduino.

Did it list mentioned device?

yes it did. many com_silabs came up. i suppose that means mentioned.

Confirming this behaviour with the Freetronics' Aduino Eleven Starter Kit.
No new ports became available when the kit was attached via USB. The unit appears to run fine using Port: tty.usbmodemfmd131 and accepts and responds to uploads
on MacOS 10.9.5 using 1.5.8 Java 6 & when using 1.5.8 Java 7

From the OSX System Report we learn that your board is based on an SiLabs CP2102 converter (or workalike), but according to your question you installed the drivers for an entirely different product from FTDI
(Arduino.cc has used FTDI in the past and CDC/ACM today, I don't believe they have ever used SiLabs so their instructions probably don't cover that, but other vendors obviously have)
Install the CP2102 drivers and it should work if you use the /dev/tty.XX device which then appears when you plug in the board.
SiLabs appears to provide the drivers at
http://www.silabs.com/products/mcu/pages/usbtouartbridgevcpdrivers.aspx
Just for sake of completeness, there are at least 5 distinct protocols/chips in use for serial-like USB communication with embedded devices:

FTDI
CDC/ACM Virtual Com Port
SiLabs CP210x
Prolific PL-2303
ch340

(Additional possibilities could include actual RS232 serial or serial-over-bluetooth)

first i installed FTDI. as it dint work and then i found this link as one of the answers were to install silabs drivers i installed them too. but not working. i tried this before only. really appreciate ur effort to help me out.

You do seem to have device files for that driver in your list.  If it didn't work when you selected those, you might have the wrong baud rate (from the chosen board configuration).  Another possibility (especially with alternate sources) is that you have a bad board - the CP2102 chip might be okay, but that doesn't mean that the AVR is, or that is has a bootloader programmed.  I'd probably try different baud rates, try burning a bootloader via ISP, etc.  But ultimately, why are you bothering with an ATmega8 board?

how do u change the baud rate? i have taken up a project which was not completed by my senior. so he has used that board.

I think you may have to create a new "board" entry in the configuration and edit the baud rate in its file, then restart the IDE. You might as well create several for different board rates.

u mean something like this ?

No, that has nothing to do with the bootloader.  You need to generate new board configurations in  a boards.txt file on your PC giving different possible baud rates, then restart the IDE and try them.

still not working. will buy a atmega328 best.
UNO will not have the same problem right?

A genuine UNO from Arduino.cc shouldn't require driver installation on OSX, and should come with a bootloader expecting a baud rate already configured in the Arduino IDE, should give you more space for programs, and is a product with a generally strong reputation for quality control.  Beyond that though, we don't actually know what the problem with your current alternate source mega8 board is.

just to add to the list - some cheaper boards use CH340 chipset
here is a blogpost on how to install the drivers on OSX
http://javacolors.blogspot.ie/2014/08/dccduino-usb-drivers-ch340-ch341-chipset.html
From that post:
You can find drivers for this chip on the web site of the chinese manufacturer, here :
http://www.wch.cn/downloads.php?name=pro&proid=5

http://arduino.cc/en/guide/macOSX
That link should almost definitely get it working for you.  Ensure (as in Step 7) that the board you have is the same one that is selected in Tools->Board.
And in step 8, since you have connected via a USB cable, it should be one of the USB named options.

its an atmega8. i have selected arduino ng or atmega 8 board.  the USB is not appearing in the serial port though the arduino is connected the PWR does light up.

If you still have problems, like me after following the above, this might help:
From this thread: http://forum.arduino.cc/index.php?topic=292284.msg2229300#msg2229300

the problem is in the spaces of the device name. To fix that you have to manually edit two (2) txt files of the arduino installation.
Go where you have installed it. In my case the path is:
/Users/MY_USERNAME/Downloads/Arduino.app/Contents/Java/hardware/arduino/avr
Inside this directory you can see files platform.txt &
  programmers.txt.
Inside these files replace -P{serial.port} with "-P{serial.port}". So
  you simply have to add the quotes.

Then restart.

source: Stack Exchange

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

sort: votes


text:
Cannot read from 2 I2C slaves consecutively
I am currently trying to communicate between 3 Arduinos using I2C. One of them acts as a master, while the rest act as slaves.
I can request data correctly from the master. But if I were to do 2 consecutive requests, I will only get data for the last request. Please assist.
Master:
#include <Wire.h>

#define BLUNO_SLAVE 0x09
#define BLUNO_SLAVE_2 0X0A

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Serial.println("Initialized as Master");
  Serial.println("Reading from slave 1 now..");
  //Wire.beginTransmission(BLUNO_SLAVE);
  Wire.requestFrom(BLUNO_SLAVE, 25);  //char occupy 1 byte
  //Wire.endTransmission();
  Serial.println("Reading from slave 2 now..");
  Wire.requestFrom(BLUNO_SLAVE_2, 30);
}

void loop () {
  while(Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }
}

Slave 1:
#include <Wire.h>

void setup() {
  Serial.begin(115200);
  Wire.begin(0x09);  //slave address
  Serial.println("Serials initialized");
}

void loop() {
  Wire.onRequest(returnData);
}

void returnData() {
  Wire.write("received master's request");
}

Slave 2:
#include <Wire.h>

void setup() {
  Serial.begin(115200);
  Wire.begin(0x0A);  //slave address
  Serial.println("initialized!");
}

void loop() {
  Wire.onRequest(returnData);
}

void returnData() {
  delay(60000);  //60 * 1000 = 60 seconds
  Wire.write("Lat: 103.123456, Lon: 1.098765");
}

Output on the master:
Initialized as Master
Reading from slave 1 now..
Reading from slave 2 now..
Lat: 103.123456, Lon: 1.098765

On top of that, I do not understand why the 1 minute delay was not executed before the slaves write the GPS coordinates.
I figured out from http://playground.arduino.cc/Main/WireLibraryDetailedReference
that each call to the requestFrom() method, RESETS the read buffer. I looked at my code back and I saw a silly mistake on the master code. So, I corrected the master code:
#include <Wire.h>

#define BLUNO_SLAVE 0x09
#define BLUNO_SLAVE_2 0X0A

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Serial.println("Initialized as Master");
  Serial.print("Slave 1: ");
  Wire.requestFrom(BLUNO_SLAVE, 25);  //char occupy 1 byte
  readData();
  //each call to requestFrom, RESETs the read buffer index
  Serial.println();
  Serial.print("Slave 2: ");
  Wire.requestFrom(BLUNO_SLAVE_2, 30);
  readData();
}

void loop () {
}

void readData () {
  while(Wire.available()) {
  char c = Wire.read();
  Serial.print(c);
 }
}

But still, I don't understand why slave2 writes the data immediately instead of waiting for 1 minute?

Using delay inside an interrupt routine isn't adviced. Try using delayMicroseconds(60000000). Also from reading the documentation, you only need to call Wire.onRequest(returnData); once, so you should move that to the setup routine.

@Gerben When I implement delayMicroseconds(60000000), it just hangs there. It does not write to the master at all. Even if I changed it to just delayMicroseconds(10), it does not write to the master.

Slave also cannot execute any codes inside a for loop.

I'm not sure I2C even allows extended pauses during communication. Maybe it just times-out.

I recommend you to just set a semaphore inside your handler. When your handler is called, set it, nothing more. In your main loop, poll for this semaphore and do your communication when true. When you receive this semaphore you can easily wait as long as you like without breaking interrupt handling. As interrupt service routines should always be as short as possible, both in terms of time and code, it is generally a bad idea to do complex communication from within or wait for something.
And don't forget the "volatile" keyword for your semaphore.

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


text:
Possible noise from the motors
I'm trying to control a self-balancing car, but it seems that the MPU6050 get dirty once my motors operate a full velocity.
I'm controlling my motors with the module L298N and with the PWM signal (pin 5, 6, 9 and 10 from the arduino).
I have read about decoupling it, with capacitors, but I don't know exactly how should I do it.
This is my code. It's a little messy (sorry for that, it just I'm still figuring out what is going on) and also an image of my project:
#include <PID_v1.h>
#include <LMotorController.h>
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif

#define MIN_ABS_SPEED 20

MPU6050 mpu;

#define DEBUG
//#define OFFSET_1

//#define STOP

// MPU control/status vars
bool dmpReady = false; // set true if DMP init was successful
uint8_t mpuIntStatus; // holds actual interrupt status byte from MPU
uint8_t devStatus; // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize; // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount; // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q; // [w, x, y, z] quaternion container
VectorFloat gravity; // [x, y, z] gravity vector
float euler[3]; // [psi, theta, phi]    Euler angle container

//PID
//double originalSetpoint = 175.8;
#ifdef OFFSET_1
      double originalSetpoint = 225;
#else
      double originalSetpoint = 184;
#endif

double setpoint = originalSetpoint;
double movingAngleOffset = 0.1;
double input, output, output_left, output_right, error;
int moveState=0; //0 = balance; 1 = back; 2 = forth
double Kp = 40;
double Kd = 0.05;
double Ki = 5;
PID pid(&input, &output, &setpoint, Kp, Ki, Kd, DIRECT);

double motorSpeedFactorLeft = 1;
double motorSpeedFactorRight = 1;
double motorSpeedFactorForward = 1;
double motorSpeedFactorBackward = 1;

//MOTOR CONTROLLER
int ENA = 5;
int IN1 = 6;
int IN2 = 7;
int IN3 = 8;
int IN4 = 9;
int ENB = 10;
//LMotorController motorController(ENA, IN1, IN2, ENB, IN3, IN4, motorSpeedFactorLeft, motorSpeedFactorRight);

//timers
long time1Hz = 0;
long time5Hz = 0;

volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady()
{
  mpuInterrupt = true;
}

void setup()
{

  // join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  Wire.setClock(400000);  // Set the SCL clock speed to 400kHz
  //Wire.setClock(200000);  // Set the SCL clock speed to 400kHz
  //TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);
  //Fastwire::setup(200, true);
#endif

  Serial.begin(115200);
  mpu.initialize();

  devStatus = mpu.dmpInitialize();

  // supply your own gyro offsets here, scaled for min sensitivity

  #ifdef OFFSET_1
      mpu.setXGyroOffset(0);
      mpu.setYGyroOffset(0);
      mpu.setZGyroOffset(0);
      mpu.setZAccelOffset(16372);
      mpu.setYAccelOffset(5);
      mpu.setXAccelOffset(2);
    #else
      mpu.setXGyroOffset(-52);
      mpu.setYGyroOffset(-12);
      mpu.setZGyroOffset(53);
      mpu.setZAccelOffset(2420);
      mpu.setYAccelOffset(2881);
      mpu.setXAccelOffset(-784);
    #endif

  // make sure it worked (returns 0 if so)
  if (devStatus == 0)
  {

    //mpu.CalibrateAccel(6);
    //mpu.CalibrateGyro(6);
    // turn on the DMP, now that it's ready
    mpu.setDMPEnabled(true);

    // enable Arduino interrupt detection
    attachInterrupt(0, dmpDataReady, RISING);
    mpuIntStatus = mpu.getIntStatus();

    // set our DMP Ready flag so the main loop() function knows it's okay to use it
    dmpReady = true;

    // get expected DMP packet size for later comparison
    packetSize = mpu.dmpGetFIFOPacketSize();

    pid.SetMode(AUTOMATIC);
    pid.SetSampleTime(10);
    pid.SetOutputLimits(-255, 255);
  }
  else
  {
    // ERROR!
    // 1 = initial memory load failed
    // 2 = DMP configuration updates failed
    // (if it's going to break, usually the code will be 1)
    Serial.print(F("DMP Initialization failed (code "));
    Serial.print(devStatus);
    Serial.println(F(")"));
  }

  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);

  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);

  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);

}
void loop()
{
  #ifdef STOP
      return;
  #endif

  // if programming failed, don't try to do anything
  if (!dmpReady) return;

  // wait for MPU interrupt or extra packet(s) available
  while (!mpuInterrupt && fifoCount < packetSize)
  {
    pid.Compute();

    output = 255;
    output_left = output * motorSpeedFactorLeft;
    output_right = output * motorSpeedFactorRight;
    if(input > (setpoint))
    {
      output_left = output_left*motorSpeedFactorForward ;
      output_right = output_right* motorSpeedFactorForward;

      Move_Forward();
    }
    else if(input < (setpoint))
    {
      output_left = output_left*motorSpeedFactorBackward ;
      output_right = output_right* motorSpeedFactorBackward;
      Move_Backward();
    }
    else
    {
      Stop();
    }
  }
  // reset interrupt flag and get INT_STATUS byte
  mpuInterrupt = false;
  mpuIntStatus = mpu.getIntStatus();

  // get current FIFO count
  fifoCount = mpu.getFIFOCount();

  // check for overflow (this should never happen unless our code is too inefficient)
  if ((mpuIntStatus & 0x10) || fifoCount == 1024)
  {
    // reset so we can continue cleanly
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
  }
  else if (mpuIntStatus & 0x02)
  {
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

    // read a packet from FIFO
    mpu.getFIFOBytes(fifoBuffer, packetSize);

    // track FIFO count here in case there is > 1 packet available
    // (this lets us immediately read more without waiting for an interrupt)
    fifoCount -= packetSize;

    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(euler, &q, &gravity);
    input = (euler[1] * 180 / M_PI + 180);
    error = input - setpoint;
//    Serial.print("\tOutput: ");
//    Serial.print(output);
    Serial.print("\tError: ");
    Serial.println(error);

  }
}

void Move_Forward() //Code to rotate the wheel forward
{

  //******RIGHT******//
      analogWrite(5, -1*output_right);
      analogWrite(6, 0);

  //******LEFT******//
      analogWrite(9, -1*output_left);
      analogWrite(10, 0);

      digitalWrite(11, HIGH);
      digitalWrite(12, LOW);
}

void Move_Backward() //Code to rotate the wheel forward
{
  //******RIGHT******//
      analogWrite(5, LOW);
      analogWrite(6, 1*output_right);

  //******LEFT******//
      analogWrite(9, 0);
      analogWrite(10, 1*output_left);

      digitalWrite(11, LOW);
      digitalWrite(12, HIGH);
}

void Stop() //Code to rotate the wheel forward
{
      analogWrite(11, LOW);
      analogWrite(12, LOW);
      analogWrite(5, LOW);
      analogWrite(6, LOW);

      digitalWrite(9, LOW);
      digitalWrite(10, LOW);
}

Keep reading about decoupling.  Learn what a capacitor does.  You’re on the right track you just need to keep looking at that.

this is the typical arrangement.

@Majenko: Are the cap leads insulated? If not, it intended that the motor case may be shorted to power leads?

No, the leads are not insulated. Two of the capacitors are soldered to the motor case. That's part of the arrangement.

Where'd you get the kit? Can you post a link? Looks pretty cool. Would be a fun project.

@Seamus The part of the motor case where the (blue) bodies of the capacitors are is plastic. A capacitor is not a short-circuit for DC: the solder joints (on the right in the photo) to the case are intentional.

Well, I have to said that at the beginning I didn't think that the arrangement that @Majenko mentioned will work.
First I tried connecting the capacitor with cables, but it still give me noise. Once I soldered it directly to the motors the noise decrease a lot.
Thanks to all. This is the image of the arrangement that I made:

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


text:
SD Library function doesnt work while using second SPI port with ESP32
i work on a group project with an ESP32. We have a lcd display and a sd card connected via the two SPI ports of the ESP32.
The card gets initialized with no problem using this code:
 bool EKG_recording::initialisation_sd() {

  SPIClass * hspi = new SPIClass(HSPI);

  if (!SD.begin(CS_Pin, *hspi))
  {
    Serial.println("No valid SD card!");
    return 0;
  }

  else if (SD.begin(CS_Pin, *hspi))
  {
    Serial.println("SD card initialized!");
    return 1;
  }
  else return 0;
}

One function i have a problem with is used to count every file on the SD card, simple enough right?
unsigned short EKG_recording::count_files_from_SD(File dir) {
  while (true)
  {
    File entry = dir.openNextFile();
    if (!entry)
    {
      // Serial.println("Anzahl der Daten");
      return counter;
    }
    counter++;
    entry.close();
  }
}

It once worked without a problem, then we integrated the two SPI ports and now i cant figure out why its not working.
This part:
File entry = dir.openNextFile();
returns false on the first call even though i am 100% sure there are 3 files on the SD card.
I call the function like this :
File root = SD.open("/");
EKG_recording_1.count_files_from_SD(root);

But why? Any help is very appreciated.
This is the begin function of the display. Since i didnt write it, i know next to nothing about it.
    void EKG_display_control::begin()
{
  // Backgroundlight off
  pinMode(TFT_LED, OUTPUT);
  disable_display_backlight();

  // Initialise Display
  tft.begin(40000000);
  touch.begin();
  tft.setRotation(ROTATION);

  layout_start_screen();
}

i use a sd adapter, connected via wires to the pins of the ESP32, also added the pinout

Its just a SD adapter you can also plug into a PC or Laptop. I soldered some pins to it and connected those with the pins of the ESP32

I also edited the begin function of the display into the main post

ok. how is SPI for the display initialized? I guess it uses the default SPI object. so everything looks ok.

I asked my team member and she said the display uses the default SPI

@Juraj i added a picture to show how the sd adapter is connected. Your help is very appreciated

Ok i found the solution. It was not too complicated. I just assumed the problem was in the code. This works well enough (dont ask me about the counter--)
  unsigned short EKG_recording::count_files_from_SD() {

  root = SD.open("/");
  root.rewindDirectory(); //Sets to beginning of directory

  while (true)
  {
    File entry = root.openNextFile();

    if(!entry){
      Serial.println("Anzahl der Daten");
      counter--;
      return counter;
    }
    counter++;
    entry.close();
  }
}

It was just because i used SD.open() always inside the class-functions, so every file root was bound to the class.

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


text:
ESP32 saving data to SD card in .csv doesnt format correctly
i want to save a vector to a .csv file on a SD Card.
I watched this tutorial on how to do it and it describes it perfectly even though its kinda dated.
My Problem is that everything is saved into the first cell of the .csv file so it gets constantly overwritten.
It should save only the first vector into the first cell, then the second vector into the second cell and so on.
I just get all three vectors with the commas into the first vector like this:
8, 9, 10
Also the header which should appear at the top is also gone.
I would really appreciate some help. Thanks!
Here is my setup and loop:
#include <iostream>
#include <string>
#include <vector>
#include "SD.h"
#include "SPI.h"
#include "EKG_data_transmision.h"

#define CS_Pin 5 // Chip Select Pin

EKG_data_transmision EKG_data_transmision;

std::vector<unsigned short> vector_1 = {1,2,3,4,5,6,7,8,9,10};
std::vector<unsigned short> vector_2 = {2,3,4,5,6,7,8,9,10,11};
std::vector<unsigned short> vector_3 = {3,4,5,6,7,8,9,10,11,12};
unsigned int for_x = 0;

void setup() {
  // open serial
  Serial.begin(9600);
  Serial.print("Init SD Card...");
  pinMode(CS_Pin, OUTPUT);

  if(!SD.begin(CS_Pin))
  {
    Serial.println("Card failed or not present");
    return;
  }

  EKG_data_transmision.vectorData = SD.open("/data.csv", FILE_WRITE);  //erstelle data.csv datei

  if(EKG_data_transmision.vectorData)
  {
    EKG_data_transmision.vectorData.println(", , , ,");
    String header = "ID, Value, Time, Whatever";
    EKG_data_transmision.vectorData.println(header);
    EKG_data_transmision.vectorData.close();
    Serial.println(header);
    Serial.println("card init sucess");
  }
  else
  {
    Serial.println("Couldnt open vector data file");
  }

}

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

  while(for_x <= 8){
    for_x++;
    EKG_data_transmision.write_vector_to_SD(vector_1, vector_2, vector_3);
    delay(1000);
  }

  delay(10000);
}

Here is my function that should save everything to the SD Card:
bool  EKG_data_transmision::write_vector_to_SD(std::vector<unsigned short> vector_ADC_1, std::vector<unsigned short> vector_ADC_2, std::vector<unsigned short> vector_ADC_3) // Übertrage
{
  dataString = String(vector_loc) + "," + String(vector_ADC_1[vector_loc]) + "," + String(vector_ADC_2[vector_loc]) + "," + String(vector_ADC_3[vector_loc]); // + "\r\n"

  vectorData = SD.open("/data.csv", FILE_WRITE);

  if(vectorData){
    //sd karte immer noch da und schau ob data.csv exisitiert
    vectorData.println(dataString);
    Serial.println("This is vector:");
    Serial.println(vector_loc);
    Serial.println("Im actually writing this:");
    Serial.println(dataString);
    vectorData.close(); // close the file
    }

  else{
    Serial.println("Error writing to file !");
}
  vector_loc++;

  return 0;
}

Thanks for your fast answer. I just changed every WRITE to APPEND. Now the values get saved into different cells but only into Row A. I thought with "," it switches into different rows. Do you have an answer to that?

in my language Excel uses ; for csv, because we have , as decimal separator

Thanks a lot for you help!! I just tried it and with ; it works perfectly.

I moved the first comment to an answer

In Arduino SD library FILE_WRITE constant instructs the function to open the file for append, but in the esp32 SD library it opens the file for rewrite. Use FILE_APPEND to open the file for append.
File file = SD.open(path, FILE_APPEND);


text:
How to improve date-time control from RTC?
I want to run cameras at a remote site from external batteries as long as possible. I need power-miser Arduino to switch battery power on/off at set intervals (e.g. 5 min) during daytime only. I am a beginner with Arduino and electronics.
Have set up 'breadboard' arduino with mosfet module for switching the power supply and RTC module, both from Freetronics (http://www.freetronics.com.au/collections/modules/products/real-time-clock-rtc-module#.V-i-S8knuPs). Following their recommendation I'm using RTC library here: http://rweather.github.io/arduinolibs/index.html
I need to refine the crude hour-based script below. Weatherley library returns separate objects e.g date.day, time.hour etc. Is there a simple way to convert to date-time object? Then calculate sunrise and sunset times based on latitude?
  #include <JeeLib.h> //  power saving library
  ISR(WDT_vect) { Sleepy::watchdogEvent(); } // Setup jeelip watchdog
  #include <SoftI2C.h> // rweather lib for RTC module
  #include <DS3232RTC.h> //rweather lib for RTC module
  SoftI2C i2c(A4, A5); // assign pins to SDA and SCL
  DS3232RTC rtc(i2c);
  RTCTime time;
  int gatePin = 12;   //  mosfet Gate connected to digital pin
  int startHour = 6; // want to replace with sunrise time
  int endHour = 19; // want to replace with sunset time

void setup()
{
 pinMode(gatePin, OUTPUT);   //  output pin for mosfet module
}

void loop()
{ // main loop starts here
  rtc.readTime(&time);  //get current time
  if (time.hour >= startHour && time.hour < endHour) // check daytime
  {   // if condition begins here
      while(time.hour < endHour ) // daytime operating period

      {   //  while loop (day) begins here
      digitalWrite(gatePin, HIGH);   // turn on gate for power supply
      Serial.flush(); //needed before sleepy
      Sleepy::loseSomeTime(30000); // low power wait
      digitalWrite(gatePin, LOW);    // turn off gate for power supply
      Serial.flush(); // needed before sleepy
      for (int i=0; i <= 3; i++){
        Sleepy::loseSomeTime(65000); // low power wait
        } // end for loop
      rtc.readTime(&time);
      } // end while loop (day)
      } //  if condition (daytime) ends here
else
  { // else condition (night time) starts here
    while (time.hour >= endHour || time.hour < startHour )
    { // while loop (night) begins here
    for (int i=0; i <= 59; i++){
    Serial.flush(); // needed before sleepy
    Sleepy::loseSomeTime(65000); // low power wait
    } // end for loop
    rtc.readTime(&time);
    } // while loop (night) ends here
// need to refine timing else hour-long wait periods can run past the end of night period
  } // else condition (night) ends here
} //  main loop ends here

I will be very grateful for advice, many thanks in advance!
EDIT: Part of my original question could be answered - see below about time-date format without using RTC. Issues with RTC appear harder than I expected. I think they will need a new question later.

I'd suggest using a light sensor. That way you can safe power if it is e.g.heavily clouded in the evening and therefor dark earlier.

Light sensor not suitable in this situation. The cameras will be used for scientific project (monitor bird activity at their nests). Therefore need to record images atset time intervals for each day from sunrise to sunset. Also I need to learn about date-time programming in Arduino for further development from this basic script.

There is a potential solution in a helpful answer to my question about understanding compiler error text.

Clarification - my comment above does not refer to complete solution to this question. Answer to q about understanding compiler error has a good explanation and solution for TestRTC compiler error - see below in this question.

I didn't mean to suggest removing the RTC. merely to suggest using a light sensor to detect sinrise and sunset. That way you don't have to enter latitude and longitude. Also data will still be collected if the time is wrong somehow (accidental reset of the RTC e.g.). So

Is there a simple way to convert to date-time object?

Not with this library. But you can find other
libraries supporting the DS3232 which work with the Arduino
Time library[]. This time library provides both the date and time in a
single object, either:

a time_t, which is just the number of seconds elapsed since a
standard “epoch”
a tmElements_t struct, which has the date and time broken into
separate elements (year, month, day, hour...).

Then calculate sunrise and sunset times based on latitude?

There are quite a few algorithms describes on the Web for that. The more
accurate ones are also the more complex.

#include <SoftI2C.h>

Doesn't your Arduino have a hardware I2C port? That would be more
efficient than software emulation.

Serial.flush(); //needed before sleepy

It's only needed if you are actually using the serial port.
Edit: I saw on your other question that you have been bitten by
an incompatibility between the Arduino Time library and the file
time.h from avr-libc. Now I just noticed that avr-libc includes the
functions sun_rise() and sun_set() that you may find
handy. Not sure they will play well with the Arduino time libraries
though. One possible incompatibility is the fact that they use different
epochs for defining time_t (year 1970 v.s. 2000).

Many thanks and sorry I don't fully understand. Using SoftI2C.h because I followed example doing it that way. Unsure whether my RTC module and atmega chip will communicate without it. Started with Uno board connected to laptop via USB, using serial window to see what was happening. At that point had to add Serial.flush(). Left it in, being unsure if needed later. Have moved the atmega chip from Uno to a breadboard with no 'peripherals' in order to minimise power usage. How do I determine whether "hardware I2C port" is available or not? Many thanks for patience with total beginner!

@jules: All the peripherals of the Arduino Uno are part of the ATmega328P chip. Thus you still have them on a “barebones” Uno (i.e. the bare ATmega). The I2C port (called TWI by Atmel) is available on pins PC4 = A4 = SDA and PC5 = A5 = SCL. You would use this port through the standard Wire library.

Great to know I have required hardware, thanks. I installed DS3232 and Time libraries you linked above. TestRTC, the example sketch for tecsmith DS3232 library gave compile errors that I cannot understand. Error text too long to add here.  Any advice on how to resolve this?

Checked both two new libraries are present, Wire was already installed. Compile TestRTC has exit status 1 'tmElements_t' does not name a type

@jules: TestRTC has #include <Time.h> on line 46. Did it find that header? Don't you have typedef struct {...} tmElements_t, TimeElements, *tmElementsPtr_t; in it?

Looked at files on my laptop, see installed Stoffregen Time library (link in your answer above) has time.h in the Time-master folder. Where do I look for  typedef struct {...} etc please?

There was an underlying issue with same-name components in different libraries. Very helpful explanation and advice in another question resolved the compile errors. Now I can now try to use the two recommended libraries for date-time.

I hope I am allowed to summarise progress. Edgar Bonet's answer above pointed me in the right direction regarding date-time format and I want to 'accept' that answer, although it did not resolve my difficulties with RTC. I need to ask a new question about RTC later.
Using the Time library Edgar Bonet recommended, I managed to set and change date-time format, and calculate duration between date-time instances. I hope my example below could perhaps be useful for other beginners. If anyone has suggestions to improve this example, please add them.
    #include <TimeLib.h> // https://github.com/PaulStoffregen/Time
    time_t tstart;

    void setup()  {
    Serial.begin(9600);
    // assume no RTC available therefore set date-time in this sketch
    // when serial monitor opens, date-time will be set as follows
    setTime(8,30,0,17,10,2016); // (hr,min,sec,day,mnth,yr);
    tstart = now();
    Serial.print("Started at: ");
    digitalClockDisplay();
    Serial.println();
    }

    void loop(){
    Serial.println("Waiting...");
    delay(20000 + random(500, 5000) );
    Serial.println();
    time_t tnow = now();
    Serial.print("Now it is: ");
    digitalClockDisplay();
    time_t duration = tnow - tstart;
    Serial.print("Duration since start: ");
    showDuration(duration);
    Serial.println();
    Serial.println();
    }

    // function to print current date-time
    // modified from example in TimeLib
    void digitalClockDisplay(){
      Serial.print("Date: ");
      Serial.print(day());
      Serial.print("-");
      Serial.print(month());
      Serial.print("-");
      Serial.print(year());
      Serial.print("  Time: ");
      Serial.print(hour());
      printDigits(minute());
      printDigits(second());
      Serial.println();
    }
    // utility function from TimeLib
    // to print leading zeros
    void printDigits(int digits){
      Serial.print(":");
      if(digits < 10)
        Serial.print('0');
      Serial.print(digits);
    }

    // function from example TimeRTCLog
    void showDuration(time_t duration){
    // prints the duration in days, hours, minutes and seconds
      if(duration >= SECS_PER_DAY){
         Serial.print(duration / SECS_PER_DAY);
         Serial.print(" day(s) ");
         duration = duration % SECS_PER_DAY;
      }
      if(duration >= SECS_PER_HOUR){
         Serial.print(duration / SECS_PER_HOUR);
         Serial.print(" hour(s) ");
         duration = duration % SECS_PER_HOUR;
      }
      if(duration >= SECS_PER_MIN){
         Serial.print(duration / SECS_PER_MIN);
         Serial.print(" minute(s) ");
         duration = duration % SECS_PER_MIN;
      }
      Serial.print(duration);
      Serial.print(" second(s) ");
    }


text:
No known conversion for argument 1 from 'Object*' to 'int*'
I'm terrible with pointers and need help passing an object to a library I'm writing. I'm getting the error no known conversion for argument 1 from 'LCDMenuItem*' to 'int*' when I try to compile. How do I pass a pointer to an object to a function?
LCDMenu.h
class LCDMenu {
    public:
    bool addItem(LCDMenuItem &item);
    private:
    LCDMenuItem *menuItems[MAX_ITEMS];
    uint8_t itemCount;
};

class LCDMenuItem {
    public:
    LCDMenuItem(char *name);
    bool setFunction(void (*function)(void));
    private:
    bool callFunction() const;
    void (*_function)(void);
    char *name;
};

LCDMenu.cpp
bool LCDMenu::addItem(LCDMenuItem &item) {
    menuItems[itemCount] = &item;
    ...
}

MySketch.ino
LCDMenuItem menuItem("Menu Option");
void setup() {
    menu.addItem(menuItem);
}

When trying to compile

bool addItem(LCDMenuItem *item);
     ^

no known conversion for argument 1 from 'LCDMenuItem*' to 'int*'

what is menuItem and where is bool addItem(LCDMenuItem *item);?

Edited. Do you mean menuItems? its an array of LCDMenuItem's addItem() is in LCDMenu.cpp

menu.addItem(menuItem); menuItem. do you have the classes in that order in .h file?

Oh, sorry. added that to MySketch.ino. I just reordered the classes putting LCDMenuItem first, didn't help.

and bool addItem(LCDMenuItem *item); reported by compiler is where?

i dont have one :) doesnt bool addItem(LCDMenuItem &item) let you pass the object like im trying to do? (obviously not)

it does. it is passing by reference and it is ok. something else is wrong.

do you have some other function called addItem in your sketch?

I don't think so. But i just got it to compile in a new sketch so now I'll track down what is causing that.


text:
NodeMCU ESP8266 Returns IP address, but cant open the web with IP address
I have used the below code with proper Wifi Address and password. The Nodemcu connects to WIfi, and displays IP address, But the IP address cannot be used to open a web page. It says "This site cant be reached". Can anyone help with this
#include <ESP8266WiFi.h>

const char* ssid = "***";
const char* password = "*******";

int ledPin = D0;
WiFiServer server(80);

void setup() {

  pinMode(ledPin,OUTPUT);
  digitalWrite(ledPin,LOW);

  Serial.begin(115200);
  Serial.println();
  Serial.print("Wifi connecting to ");
  Serial.println( ssid );

  WiFi.begin(ssid,password);

  Serial.println();
  Serial.print("Connecting");

  while( WiFi.status() != WL_CONNECTED ){
      delay(500);
      Serial.print(".");
  }

  Serial.println();

  Serial.println("Wifi Connected Success!");
  Serial.print("NodeMCU IP Address : ");
  Serial.println(WiFi.localIP() );

  server.begin();
  Serial.println("NodeMCU Server started");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

}

void loop() {

    // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("Hello New client");
  while(!client.available()){
    delay(1);
  }

   // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

   // Match the request

  int value = LOW;
  if (request.indexOf("/LED=ON") != -1)  {
    digitalWrite(ledPin, HIGH);
    value = HIGH;
  }
  if (request.indexOf("/LED=OFF") != -1)  {
    digitalWrite(ledPin, LOW);
    value = LOW;
  }

// Set ledPin according to the request
//digitalWrite(ledPin, value);

  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("");

  client.print("Led pin is now: ");

  if(value == HIGH) {
    client.print("On");
  } else {
    client.print("Off");
  }
  client.println("

");
  client.println("<button>Turn On </button>");
  client.println("<button>Turn Off </button>
");
  client.println("");

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");

}

you must read the request. flush() doesn't do it. browsers don't like a response before they finished to send a request. see the WiFiWebServer example in the IDE examples menu

the example is now renamed to WiFiManualWebServer

Are you sure you are on the same wifi network as the esp unit ? eg. don't do it from your cellular connected phone.

Hi, did you find the solution to this problem?


text:
How can I connect multiple different sensors that uses the same pins?
I'm doing a project on Arduino Uno and it requires me to connect 3 different sensors together: Waveshare 2.9 E-paper, MFRC522 RFID Reader and a ESP8266 wifi module. problem is, The e-paper and RFID uses the same multiple digital pins. How can I connect all of them together in a beardboard?
Edit:
The E-Paper uses:
e-paper 3V3 -> Arduino 3V3
e-paper GND -> Arduino GND
e-paper DIN -> Arduino D11
e-paper CLK -> Arduino D13
e-paper CS -> Arduino D10
e-paper DC -> Arduino D9
e-paper RST -> Arduino D8
e-paper BUSY -> Arduino D7

The rfid uses:
SDA --> Digital 10
SCK --> Digital 13
MOSI --> Digital 11
MISO --> Digital 12
IRQ --> unconnected
GND --> GND
RST --> Digital 9
3.3V -->3.3V

The wifi uses:
GND --> GND
VIN --> 3.3v
Enable --> 3.3V
TX --> RX
RX --> TX

I'm very new to electronics so i'm sorry if something does not make sense
I'm using library, code and instructions from this 3 websites:
E-paper ( Waveshare 2.9 E-paper): https://www.instructables.com/id/Getting-Started-With-E-Paper-Display-Modules/
RFID (MFRC522 RFID Reader): https://randomnerdtutorials.com/security-access-using-mfrc522-rfid-reader-with-arduino/
Wi-Fi (ESP8266 wifi module): https://www.hackster.io/jeffpar0721/add-wifi-to-arduino-uno-663b9e
Thanks!

Such a question cannot be answered in general, but only with full specifics of how each pin is being used.  In many cases you will be able to relocate one function to a different pin, or the pins are being used in ways (such as SPI or I2C busses) which are already designed to be shared.  But without full details this is unanswerable and will have to be closed.

@Arthane, you can use the preview under your post to check formatting before submission. Use the {} code tags to format as in my tidy-up. I didn't fix your "beardboard" as it looks interesting.

You are lucky, the two devices creating the conflict both use the same pins because they both use the same interface, SPI to be precise, which allows to have multiple devices connected using different Chip Select pins, abbreviated as CS.
Of the two libraries, one allows to define the CS pin (RFID module), the other has it hardcoded (ePaper). So, when declaring your RFID library, you should use the constructor that allows to define the chip select pin:
void PCD_Init(byte chipSelectPin, byte resetPowerDownPin);

This means in your code you should use:
PCD_Init(6,8) rfid;

The above also implies one of your RFID connections must be changed: what was previously SDA --> Digital 10 is now going to be SDA --> Digital 6. Please note I picked pin 6 randomly among the pins that seem unused by your code, but any other unused pin will be a good choice, including analog pins.
BTW, the web page about the RFID module uses a pin naming which causes a lot of confusion because it mixes up SDA with MISO and MOSI: those names are used in two different types of interface, the former is called I2C or TWI, the latter SPI. On Arduino the two interfaces share a couple of pins, but they are very different in many different ways.
In your case both modules use SPI, which is good for you.


text:
SPI Arduino Due conflict with pinMode(), bug?
Consider the following minimal example, where I set pinMode before calling SPI functions:
#include <SPI.h>

void setup() {
  pinMode(10, OUTPUT);
  SPI.begin(10);
  SPI.setDataMode(10,SPI_MODE1);
}

void loop() {
  delay(1000);
  SPI.transfer(10,1);
}

Now when SPI.transfer(10,1) is called in loop(), I always see that the slave selected pin goes down to 1.65V, but not 0 as it should! (see image below)

If we don't call pinMode(), like this:
#include <SPI.h>

void setup() {
  SPI.begin(10);
  SPI.setDataMode(10,SPI_MODE1);
}

void loop() {
  delay(1000);
  SPI.transfer(10,1);
}

We get what we would expect when calling SPI.transfer:

Is that a bug or do you have an explanation for that behaviour?
Thank you very much in advance for your time and interest!

Shouldn't it be SPI.setDataMode(10, SPI_MODE1);? Also only the second one is useful, as begin() calls setDataMode. Looking at the source code it looks like the SPI library doesn't alter the pin you specified (though I don't know ARM).

Ja you are right, by accident I am calling setDataMode() twice. Tomorrow I will test the effect of SPI.setDataMode(10, SPI_MODE1); But why calling pinMode() has this effect is still not clear or? @Gerben

@Gerben I modified my post

It might have something to do with the internal pull up resistor. According to the SAM3X/A datasheet,

Control of the pull-up resistor is possible regardless of the
configuration of the I/O line.
After reset, all of the pull-ups are enabled.

If you dig through all the include files you find:
../Arduino/hardware/arduino/samd/cores/arduino/wiring_digtal.c

Line 124 defines the pinMode(uint32_t ulPin, uint32_t ulMode) function. Examining the switch/case statement for INPUT vs INPUT_PULLUP vs OUTPUT you see the following:

INPUT sets a register to reg = PORT_PINCFG_INEN.
INPUT_PULLUP sets a register to  reg = (PORT_PINCFG_INEN | PORT_PINCFG_PULLEN)
OUTPUT sets a register to reg &= ~PORT_PINCFG_INEN.

The 'register' in each case is the same. I cannot for the life of me find what value PORT_PINCFG_INEN or PORT_PINCFG_PULLEN are defined as, but they're no doubt just 8-bit masks (they're cast to uint8_t when they're assigned to the 'register'). Thus, we can assume that whichever bit controls input/output is active when asserted, as is the pullup bit. For example:
 PORT_PINCFG_INEN   = b'00000001';
 PORT_PINCFG_PULLEN = b'00000010';
~PORT_PINCFG_INEN   = b'11111110';

If pull-ups are enabled after reset, we can say that on reset:
 reg = b'xxxxxx1x';

Point (3) above strongly implies that the instruction is:
 reg = b'xxxxxx1x' & 'b11111110';
   so
 reg = b'xxxxxx10'; // pull-up is enabled!

Therefore, if you call pinMode(X, OUTPUT) before anything else you will end up with the pullup resistor enabled. Setting the pin to an input will clear the pullup enable bit, after which you can set the pin to an output and the bit will remain clear.
However, the whole arguement falls down with the simple fact that if you don't call pinMode() at all, the problem doesn't occur...


text:
Arduino + WizFi 210 (WiFi) HTTP POST
I would like to do an HTTP POST to Carriots. I saw a few tutorials.
Both of them are using ethernet instead of WiFi. I realize the ways of using Arduino WiFi shield and WizFi Shield are a bit different. What do I need to do to run a basic server using the WizFi Shield?
Code:
/******************************************************************
 WizFiShield Web Client Test Example
*****************************************************************/

// WizFiShield communicates using SPI, so include the SPI library:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <SPI.h>
#include <WizFi2x0.h>
#include <WizFiClient.h>
#include <TimerOne.h>

#define SSID    "EricLeong3"        // SSID of your AP
#define Key     "ericChoong91"  // Key or Passphrase
// Wi-Fi security option (NO_SECURITY, WEP_SECURITY, WPA_SECURITY, WPA2PSK_SECURITY)
#define Security        WPA2PSK_SECURITY
#define APIKEY  "xxxxxxxxx" // Replace with your Carriots apikey
#define DEVICE  "fypSensors@eric3231559.eric3231559"

WizFi2x0Class myWizFi;
WizFiClient myClient;
TimeoutClass ConnectInterval;
boolean Wifi_setup = false;

///////////////////////////////
// 1msec Timer
void Timer1_ISR() {
  myWizFi.ReplyCheckTimer.CheckIsTimeout();
}
//
//////////////////////////////

void setup() {
  byte retval;
  Serial.begin(9600);
  Serial.println("\r\nSerial Init");
  // initalize WizFi2x0 module:
  myWizFi.begin();
  ConnectInterval.init();
  // Socket Creation with Server IP address and Server Port num
  myClient =  WizFiClient("82,223,244,60", 80);
  // Timer1 Initialize
  Timer1.initialize(1000); // 1msec
  Timer1.attachInterrupt(Timer1_ISR);
  myWizFi.SendSync();
  myWizFi.ReplyCheckTimer.TimerStart(3000);
  Serial.println("Send Sync data");
  while(1) {
    if(myWizFi.CheckSyncReply()) {
      myWizFi.ReplyCheckTimer.TimerStop();
      Serial.println("Rcvd Sync data");
      break;
    }
    if(myWizFi.ReplyCheckTimer.GetIsTimeout()) {
      Serial.println("Rcving Sync Timeout!!");
      // Nothing to do forever;
      for(;;)
      ;
    }
  }
  ////////////////////////////////////////////////////////////////////////////
  // AP association
  while(1) {
    retval = myWizFi.associate(SSID, Key, Security, true);
    if(retval == 1) {
      Serial.println("AP association Success");
      Wifi_setup = true;
      break;
    } else {
      Serial.println("AP association Failed");
    }
  }
}

void loop() {
  Serial.println("apleleee ");
  uint8_t retval;
  retval = myClient.connect();
  if(retval == 1) {
    String json = "{\"protocol\":\"v2\",\"device\":\""+String(DEVICE)+"\",\"at\":\"now\",\"data\":{\"Air Temperature\":\"58\",\"Humidity\":\"59\"}}";
    Serial.println("Connected! ");
    //myClient.write((byte *)"GET /search?q=WizFi210 HTTP/1.0\r\n\r\n");
    myClient.write((byte *)"POST /streams HTTP/1.1");
    myClient.write((byte *)"Host: api.carriots.com");
    myClient.write((byte *)"Accept: application/json");
    myClient.write((byte *)"User-Agent: Arduino-Carriots");
    myClient.write((byte *)"Content-Type: application/json");
    myClient.write((byte *)"carriots.apikey: ");
    myClient.write((byte *)APIKEY);
    myClient.write((byte *)"Content-Length: ");
    byte thisLength = json.length();
    myClient.write(thisLength);
    myClient.write((byte *)"Connection: close");
    myClient.write((byte *)"");
    myClient.write((byte *)"{\"protocol\":\"v2\",\"device\":\"");
    myClient.write((byte *)DEVICE);
    myClient.write((byte *)"\",\"at\":\"now\",\"data\":{\"Air Temperature\":");
    myClient.write((byte *)"58");
    myClient.write((byte *)",\"Humidity\":");
    myClient.write((byte *)"59");
    myClient.write((byte *)"}}");
  } else
    Serial.println("Connection Failed");
  }

The response I get on the serial monitor
Serial Init
Send Sync data
Rcvd Sync data
AT

Rcvd Reply: [ERROR]
[ERROR]
Timeout  with ERROR reply
AP association Failed
AT

Rcvd Reply: õAT
õAT
-1

Rcvd Reply: [ERROR: INVALID INPUT]
[ERROR
INVALID
INPUT]
-1

Rcvd Reply: AT
AT
-1

Rcvd Reply: [OK]
[OK]
ATE0

Rcvd Reply: ATE0
ATE0
-1

Rcvd Reply: [OK]
[OK]
AT+XDUM=0

Rcvd Reply: [OK]
[OK]
AT+BDATA=1

Rcvd Reply: [OK]
[OK]
AT+WD

Rcvd Reply: [OK]
[OK]
AT+WM=0

Rcvd Reply: [OK]
[OK]
AT+WPAPSK=EricLeong3,ericChoong91

Rcvd Reply: Computing PSK from SSID and PassPhrase...
Computing
PSK
from
SSID
and
PassPhrase...
-1

Rcvd Reply: [OK]
[OK]
AT+NDHCP=1

Rcvd Reply: [OK]
[OK]
AT+WA=EricLeong3

Rcvd Reply:     IP              SubNet         Gateway
    IP              SubNet         Gateway
IP
SubNet
Gateway

Rcvd Reply:  192.168.1.42: 255.255.255.0: 192.168.1.1
 192.168.1.42: 255.255.255.0: 192.168.1.1
192.168.1.42
192.168.1.42
255.255.255.0
255.255.255.0
192.168.1.1
192.168.1.1

Rcvd Reply: [OK]
[OK]
AP association Success
apleleee
AT+DNSLOOKUP=82,223,244,60,3,5

Rcvd Reply: [ERROR: INVALID INPUT]
Token: [ERROR

May I know what's wrong with the code? Why does it show a token error instead of success? What I am trying to do is posting an HTTP POST request to Carriots, which is a place to do my m2m things. I am still wondering which part I am missing. I referred to few sources such as
http://forum.carriots.com/index.php/topic/61-wireless-gardening-with-arduino-cc3000-wifi-modules/page-2
https://github.com/Wiznet/WizFiShield

Welcome to Arduino SE. I'm sorry we can't provide general tutorials here. Is there a specific issue you're struggling with?

@PeterR.Bloomfield I had edit the question.hopefully i can get some help here

What he meant was asking for a tutorial somewhere is generally not accepted since we strive to be the information, not a collection of links. I edited your question to narrow it down a bit...

The library provides an example for a server.
Here's what it looks like:
/******************************************************************
 WizFiShield Web Server Test Example

 A simple web server that shows "Hello World" string

 Circuit:
 WizFi2x0 connected to Arduino via SPI

 RST: pin 2  // Output
 DRDY: pin 3  // Input
 CSB: pin 4  // output
 MOSI: pin 11  // output
 MISO: pin 12  // input
 SCK: pin 13  // out

 Created 27 Sep. 2012
 by James YS Kim  (jameskim@wiznet.co.kr, javakys@gmail.com)

 Modified 27 May. 2013
 by Jinbuhm Kim  (jbkim@wiznet.co.kr, jinbuhm.kim@gmail.com)
*****************************************************************/

// WizFi210 communicates using SPI, so include the SPI library:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <SPI.h>
#include <WizFi2x0.h>
#include <WizFiClient.h>
#include <WizFiServer.h>
#include <TimerOne.h>

#define SSID    ""        // SSID of your AP
#define Key     ""  // Key or Passphrase
// Wi-Fi security option (NO_SECURITY, WEP_SECURITY, WPA_SECURITY, WPA2PSK_SECURITY)
//#define Security        WPA_SECURITY

#define MAX_SOCK_NUM    4

unsigned int SrcPort = 80;

WizFi2x0Class myWizFi;
WizFiClient myClient[MAX_SOCK_NUM];//(SIP, ServerPort);
WizFiServer myServer(SrcPort);

boolean Wifi_setup = false;

///////////////////////////////
// 1msec Timer
void Timer1_ISR()
{
  myWizFi.ReplyCheckTimer.CheckIsTimeout();
}
//
//////////////////////////////
void setup() {
  byte retval, i;

  Serial.begin(9600);
  Serial.println("\r\nSerial Init");

  for(i=0; i<MAX_SOCK_NUM; i++)
    myClient[i] =  WizFiClient();

  myWizFi.begin();

  // Timer1 Initialize
  Timer1.initialize(1000); // 1msec
  Timer1.attachInterrupt(Timer1_ISR);

  myWizFi.SendSync();
  myWizFi.ReplyCheckTimer.TimerStart(3000);

  Serial.println("Send Sync data");

  while(1)
  {
    if(myWizFi.CheckSyncReply())
    {
      myWizFi.ReplyCheckTimer.TimerStop();
      Serial.println("Rcvd Sync data");
      break;
    }
    if(myWizFi.ReplyCheckTimer.GetIsTimeout())
    {
      Serial.println("Rcving Sync Timeout!!");
      return;
    }
  }

  ////////////////////////////////////////////////////////////////////////////
  // AP association
  while(1)
  {
    byte tmpstr[32];

    retval = myWizFi.associate(SSID, Key, Security, true);

    if(retval == 1){
      myWizFi.GetSrcIPAddr(tmpstr);
      Serial.println("WizFi2xo AP Associated");
      Serial.print("MY IPAddress: ");
      Serial.println((char *)tmpstr);
      Wifi_setup = true;
      break;
    }else{
      Serial.println("AP association Failed");
    }
  }

  if(myServer.begin())
    Serial.println("Server Listen OK");
  else
    Serial.println("Server Listen Failed");
}

void loop()
{
  uint8_t retval, i;
  byte rcvdBuf[129];

  memset(rcvdBuf, 0, 129);

  if(Wifi_setup)
  {
    myWizFi.RcvPacket();
    for(i=0; i<MAX_SOCK_NUM; i++)
    {
      if(myClient[i].available()){
         retval = myClient[i].read(rcvdBuf);
         if(retval > 0)
         {
           Serial.print("CID[");
           Serial.print((char)myClient[i].GetCID());
           Serial.print("]");
           Serial.println((char *)rcvdBuf);

           if((rcvdBuf[retval - 1] == 0x0A) && (rcvdBuf[retval - 2] == 0x0D) && (rcvdBuf[retval - 3] == 0x0A) && (rcvdBuf[retval - 4] == 0x0D))
           {
             Serial.print("Receiving Completed");
             myClient[i].write((byte *)"HTTP/1.1 200 OK\r\n");
             myClient[i].write((byte *)"Content-Type: text/html\r\n");
             myClient[i].write((byte *)"\r\n");
             myClient[i].write((byte *)"Hello World !\r\n");

             delay(100);
             myClient[i].disconnect();
           }
         }
       }
    }
  }
}

Using the WizFiServer class, it seems to assign a WizFiClient instance to each HTTP socket connection. It can then call clientName.write( /* Data to be sent to client */ ); and clientName.read(); to get values.
Once it is done with the client, it can free up resources by calling clientName.disconnect();.


text:
How can I get two Arduinos to "talk" to each other?
I'm pretty new to this whole thing so please excuse my lack of familiarity with terminology.
I'm looking to build two "buzzers" of sorts. One will live on the ground floor and the other will live on the fourth floor. There is wireless internet as well as wired internet available to connect the two.
This is the basic idea. I might put more frills in later. Both buzzers have one button and one LED. I want it so that once a buzzer's button is pressed, the LED lights on both buzzers will light up. Then, only when buzzer two's button is pressed, will the LED lights on both buzzers turn off.
I'm pretty tied up on the two Arduinos communicating with each other. Is it possible to do something like that?

My favourite way to link devices together is to use these XRF modules, which you can get on ebay for £12 or less with an antenna. They talk to each other over long distances (upto 1000m with wire antenna) using a configurable encrypted messaging system (AES128 if I remember correctly), and they work for me really well. Easy to attach better antennae to them as well :)

Wired
Communication speed is not a factor - you only have to transmit an on/off signal. The simplest method would be to run a 4-wire cable, like a telephone cable, between the two.
The wires would be

GND
5V (maybe)
Ground floor output -> fourth floor input
Fourth floor output -> ground floor input

The steps are

Both wire 3 and 4 start LOW When ground floor button is pressed, ground floor led goes on, wire 3 is set HIGH.
Fourth floor is monitoring wire 3, when it goes HIGH, fourth floor led goes on, and    wire 4 is set HIGH
Ground floor is monitoring wire 4, when it goes HIGH, ground floor led goes off, and wire 3 is set LOW
Fourth floor is monitoring wire 3, when it goes LOW, fourth floor led goes off,    and wire 4 is set LOW
Ground floor is monitoring wire 4, when it    goes LOW, it begins waiting for a button press again.

Wire 2 can be used for 5V (or 3.3V depending on the Arduino) so that one of the devices can be powered off the other.
Wireless
The other option is to attach an RF transceiver to each Arduino, something like this would be good as it has 100m line-of-site range which you might need to get through 4 floors of concrete.
Learning
Start off with the simple wired method shown above. When it is working, connect wire 3 and 4 into the RX and TX pins and try to communicate using the serial port. Finally, move on to the wireless transceivers.

Benefits of a networked device:

Fairly fast because it has to be able to transfer large amounts of data
Can be compatible and used with computers, servers, and mobile devices. You might also only have to have one Arduino (if the second one would only be acting as a bridge between the protocol and the computer)
Why wouldn't you want to have a networked Arduino :)

So that rules out the protocols I2C, UART, and SPI. I find Bluetooth too hard to work with (it seems to have only a short range) using an Arduino. That leaves us with Wifi, wired network connection, and USB. USB would be best if you could run a short wire, but most USB peripherals aren't really designed to be used 100 feet away from the computer.
With ethernet and Wifi left, I'm going to advise you to go with a wired connection if possible. Benefits of keeping it wired:

Even faster (with lower latiencies)
Lower cost to interface with
More reliable than Wifi
No pesky Wifi passwords

tl;dr: Without a ton of info, wired internet (a.k.a. ethernet) seems to be the best choice.  Other wireless options don't provide the distance you need and you (probably) can't run a wire with another protocol.

Remember that for attaching 2 like devices like Arduino you'll need a crossover cable.


text:
How to program an Arduino Uno Pro with a makefile?
I'm using Arduino Makefile to compile sketches for Uno and Mega boards. I'm now trying to compile a sketch for an Arduino Uno Pro, which is an Uno with a replaced chip to give it features more like a Mega.
When writing a makefile to compile for this board, which BOARD_TAG should I use? I don't see this board listed in the official Arduino or Arduino Makefile docs.

After you edit your boards.txt file to incorporate the Arduino Uno Pro section from near the end of that Arduino Uno Pro webpage at hobbytronics.co.uk that you referenced, the board tag list produced by make show_boards will include the following line:
uno_pro       Arduino Uno*Pro

indicating the tag should be uno_pro.

I also had to copy over a pins_arduino.h file, but yeah, that was it. I thought it required something more the makefile.

@Cerin, glad you got it to work ... I've been impressed by the documentation quality and the ease of use of this particular Arduino Makefile system.  BTW, if copying the pins_arduino.h file fixed the other problem you posted, you probably could either delete that question or answer it.


text:
Custom source directory
How do you specify a custom location for your sketch?
I want my code to be located in a src folder, but when I try to compile my main.ino, arduino complains "The file main.ino needs to be inside a sketch folder named "main". How do I disable this arbitrary restriction?

I found I could accomplish this using the arduino-builder tool. I created this simple bash script to do the compilation:
#!/bin/bash
CURRENT_DIR=`pwd`
mkdir -p $CURRENT_DIR/.build
arduino-builder -compile -hardware /usr/share/arduino/hardware -tools /usr/share/arduino/hardware/tools -tools /usr/share/arduino/tools-builder -libraries $CURRENT_DIR/lib -fqbn arduino:avr:uno -build-path $CURRENT_DIR/.build $CURRENT_DIR/src/main.ino

You can't. It's a feature of Processing, on which the Arduino IDE is based.

The tools ino and ano do this, still using the Arduino internals to do the compilation. I'd like to do this through the official command line interface, because those tools are no longer maintained.


text:
How to wire an analog IR sensor for digital input?
How do you wire a phototransistor so that it outputs a clean digital signal in response to certain light levels?
I've wired a QRD1114 to an Arduino analog pin to detect a white or black surface. However, I want to use this sensor to detect fast movement of a black/white color strip, and since analogRead() can take up to 100µs and I'd rather use the ADC pin for other sensors, I want to rewire this so I can read the same signal with digitalRead().
In order to do this, the sensor needs to output less than 2.3V for white and more than 2.5V for black. I'm pretty close, but I'm having trouble with black. For white, the voltage drops to 0.7V, so that reads perfectly, but black still reflects a lot of IR, so it typically reads 2.3V, which still translates as a LOW value.
My sensor's circuit is a pretty basic voltage divider:

R1 is the Arduino's built-in 20k pullup. R2 is a variable resistor I've tried using to "shift" the voltage level up for the black case. Unfortunately, I've found this very difficult to calibrate. The larger I make R2, the higher the black-case voltage gets...but so does the white-case voltage. By the time I make R2 large enough so that black registers as HIGH, white also registers as high. Through trial and error, I found 25.7k ohms is the sweet spot, but the difference in voltage between the two is about 0.5V, which makes me nervous about getting false readings.
I've measured the phototransistor's resistance in each case, and for black it reads as 12.5k ohms while for white it reads as 9.7k ohms.
Given my 25.7k calibration resistance, the voltage divider should output for black:
Vout = Vin * R2/(R1 + R2)

5 * (12500+25700)/(20000 + 12500+25700) = 3.2V

and for white:
5 * (9700+25700)/(20000 + 9700+25700) = 3.1V

However, for black, my meter reads 2.3V for black and 2.0V for white.
Why do my meter measurements not match the voltage divider formula? Am I wiring this voltage divider correctly?
What can I do to get a cleaner digital output without complicating the circuit too much?

Would you consider using a comparator (op amp) too complicated?

Per datasheet, the QRD1113 / QRD1114 is a "Reflective Object Sensor", not a color sensor.  If the sensor does its job properly, you will get about the same signal for a black object as for a white object.  That said, what happens if you add an external 5KΩ – 15KΩ pullup in place of the internal pulllup?  You might also try a bridge arrangement

@jwpat7, When you're only talking about two colors, as in my case, then yes, it's very much a color sensor, and many people successfully use it for this purpose. You see the color black because a black material doesn't reflect most wavelengths... And no, a different pullup does nothing.

@Marla, Yes, that would be too complicated.

Multimeters will affect the voltage a bit. Especially if you are using such high value resistors. Better connect directly to the arduino, and have the arduino light an led, if it reads high. I'd add a potentiometer, so you can trim the values. Also, not every input has the same 2.4V "tipping point". (I'd experiment with a lower value for R1, and remove R2.)

@Gerben, I'm puzzled by this. The input impedance of most modern meters is quite high, mine is rated at '> 10 MΩ' I would think that that should make little or no difference to the voltages in this circuit. Or am I missing something?

Near the bottom of:
https://learn.sparkfun.com/tutorials/qrd1114-optical-detector-hookup-guide
shows a graph of the voltage for a white surface and a black surface. If I understand your question correctly, I think you can get your desired results by controlling the distance between the sensor and the surface. For example, at 0.5mm white reads about 0.1V while black reads about 3.2V

A 330Ω current-limiting resistor and a 10kΩ pull-up resistor were used in their circuit.

Hope this helps.


text:
Waterproofing Arduino
the project i'm working on is a weather station out door and for that i need to to give arduino at least some sort of protection from moisture.
https://www.instructables.com/id/Arduino-Weather-Station-AWS/
putting arduino in a box might work but the humidity where i live is very high it's rain a lot but the cold is not much. looking for ideas to waterproof arduino board please.
also can arduino work everyday of year without problem?

Google "Conformal Coating" and "Epoxy Potting Compound".

Using a waterproof enclosure? Just make sure the heat doesn't get too high.

You can just solder everything you need to the Arduino (I would recommend using an Arduino Mini since it has no communication port) and coat it with Silicon Conformal Coating. It creates a silicon layer on top of the PCB that would not let any moisture through. Or you can just put it in a case and cover it with epoxy, that will be even more protection, but there will be no more access to the board unless you foresee it.


text:
Multiplication operator with or without braces
I have written a simple calculator program for an LCD keypad shield. It works fine except for the multiplication case. It gives me zero. However, I have noticed that when I enclose the expression num1 * num2 in parenthesis it does work. Why is that so?
#include <LiquidCrystal.h>

LiquidCrystal lcd (8, 9, 4, 5, 6, 7);

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.clear();
}

void loop() {

  float ans = 0;

  lcd.print("Starting Calc");
  delay(500);

  lcd.clear();
  lcd.print("Enter 1st Num");
  while (Serial.available() == 0) {}
  float num1 = Serial.parseFloat();

  lcd.clear();
  lcd.print("Enter 2nd Num");
  while (Serial.available () == 0) {}
  float num2 = Serial.parseFloat();

  lcd.clear();
  lcd.print("Enter Operator");
  lcd.setCursor(0, 1);
  lcd.print(" R+, U*, D/, L- ");
  int val = analogRead(A0);

  while (val > 1000) {
    val = analogRead(A0);
  }

  if (val == 0) { // addition
    ans = num1 + num2;
  }

  if (val >= 97 && val <= 98) { // multiplication
    ans = num1 * num2;
  }

  if (val >= 253 && val <= 254) { // division
    ans = num1 / num2;
  }

  if (val >= 407 && val <= 408) { // subtraction
    ans = num1 - num2;
  }

    lcd.clear();
    lcd.print("Answer is = ");
    lcd.print(ans);
    delay(2000);
}

Modified Code
#include <LiquidCrystal.h>

LiquidCrystal lcd (8, 9, 4, 5, 6, 7);

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.clear();
}

void loop() {

  float ans = 0.0;

  lcd.print("Starting Calc");
  delay(500);

  lcd.clear();
  lcd.print("Enter 1st Num");
  while (Serial.available() == 0) {}
  float num1 = Serial.parseFloat();

  lcd.clear();
  lcd.print("Enter 2nd Num");
  while (Serial.available () == 0) {}
  float num2 = Serial.parseFloat();

  lcd.clear();
  lcd.print("Enter Operator");
  lcd.setCursor(0, 1);
  lcd.print(" R+, U*, D/, L- ");

  // here we split our logic.. first repeatedly read input value until valid operator read
  // secondly we perform the arithmetic operation accordingly

  char input = ' '; // space = no operator read so far
  int val;

  do {
    val = analogRead(A0);
    // see how if statements are written concisely for readability
    // if only one statement after condition you can skip curly brackets
    if (val == 0) input = '+';
    if (val >= 97 && val <= 98) input = '*';
    if (val >= 253 && val <= 254) input = '/';
    if (val >= 407 && val <= 408) input = '-';
  } while (input == ' ');

  Serial.println(input);
  Serial.println(num1);
  Serial.println(num2);
  delay(1000);

  // perform arithmetic operation
    switch (val) { // not written in a standard way but very readable
      case '+': ans = num1 + num2; break;
      case '-': ans = num1 - num2; break;
      case '*': ans = num1 * num2; break;
      case '/': ans = num1 / num2; break;
    }

  lcd.clear();
  lcd.print("Answer = ");
  lcd.print(ans);
  delay(2000);
}

I think you're looking in the wrong place. The brackets make no difference. Instead you should be looking at your usage of parseFloat.

I also don't think that brackets don't make a difference. However, I don't see any problem with my usage of parseFloat. It seems to work for other operations. Do you see an issue here?

The parentheses should definitely make no difference. My guess is that
what you saw was just a coincidence. The analog ranges you have defined
are extremely narrow. Any instability in the circuit can throw your
readings out of the expected ranges. If you get a reading that does not
fit in any of those ranges, none of the if conditions will evaluate to
true, and you end up with the result being zero, as this is how you
initialized the variable ans.
I suggest two changes to your program:

Make the ranges wider
Repeatedly read the analog input until you get a valid reading.

To illustrate the second item, here is a code snippet that splits the
logic of you if chain in two parts: first read the operator
(repeatedly until we get a valid reading), then perform the operation:
// Read the operator.
char op = ' ';  // space = no operator read so far
do {
    int val = analogRead(A0);
    if (val == 0) op = '+';
    if (val >= 97 && val <= 98) op = '*';
    if (val >= 253 && val <= 254) op = '/';
    if (val >= 407 && val <= 408) op = '-';
} while (op == ' ');

// Perform the operation.
switch (op) {
    case '+': ans = num1 + num2; break;
    case '*': ans = num1 * num2; break;
    case '/': ans = num1 / num2; break;
    case '-': ans = num1 - num2; break;
}

Thanks a lot for your clear explanation. I fully agree that I was getting 0 occasionally due to circuit instability. I didn't know about do... while loops but now I do :) The program should have worked now but mysteriously the "ans" variable is not being updated by switch case. I tried it with if statements but it also doesn't work. I wonder what's causing this? P.s. I have uploaded the modified code in the original post.

@Zaffresky: Oops, my bad! The switch should be done on the selected operator, not on the analog value. I just edited the answer.

Bingo. It works nicely :) Thanks


text:
Arduino Nano 33 IOT issue
Nano 33 IOT is not detecting by windows . When i plug the usb cable only green light on the board.
Board is installed from the board manager. the cable is usb DATA cable and not charging cable. I tried the double press on the reset button but nothing happen. The L light is Off and the green light isnt flashing.
I plugged the board into another usb port, the same issue. I tried the board on my friend computer also but no luck. I dont have ATmel ICE or any other debugger like j-link.
https://www.youtube.com/watch?v=C0tXa0uxv5c
I hope someone can explain what is the issue, is it hardware or software.

much clearer ... the first sentence describes the problem, the rest of the post is more or less irrelevant because it depends on proper windows detection ... may be a missing windows driver or may be hardware .... try plugging into a linux machine and looking at the kernel messages (dmesg) .... you can use a linux liveCD like Knoppix or Linux Mint to boot your PC

Windows 10, 64bit. The second board ( Nano 33 ble sense) working on the same usb port. after I spent time on google I found that the problem related to missing bootloader for some reason. Many faced the same issue but few of them were successful to recover the board by double press on the reset button.

Not an answer to your problem, but just some information you might want to know. Nano 33 BLE Sense is a very different board from Nano 33 IoT, even their name suggesting they belong to the same family, but they use different MCUs. Nano 33 IoT is based on Microchip's SAMD21 32-bit ARM Cortex-M0 MCU. But Nano 33 BLE is actually use the MCU within the uBlox module which is a Nordic ARM chip. Both MCU have on-chip USB supports.

One way to solve the Nano 33 IoT reset problem is to replace the 100k resistor connected to the reset pin with a 10k resistor.

I mentioned the Nano 33 ble sense because i bought them from the same store and not to forget. I got Seeed wio lite w600 wich has the same MCU  SAMD21 . Both broads with different mcu working fine and to eliminate the issue between the three boards. I had to mention the names.

I guess i have the same issue.
Did you solve the issue?
If yes could you please share the hardware and software you used to do it or the link to the process you follow?
thank you.

@y78, it is in the answers

If you upload to a SAMD board like the MKR boards or the Nano 33 IoT with Nano 33 BLE selected in Tools menu of Arduino IDE, the upload is executed and deletes the bootloader of the SAMD MCU.
The problem is that bossac uploader doesn't check the chip, because it was developed only for the SAMD chips, but Arduino created a bootloader for the Nano 33 BLE nRF52 MCU to use the SAMD bossac uploader.
The SAMD boards use the native USB support of the MCU, so without a bootloader or good sketch running the USB doesn't work.
You have to restore the bootloader on Nano 33 IoT. It is done over the SWD pads on the bottom side of the board. You can use a SWD programmer or other Arduino board with the Adafruit DAP library.
You can use your Nano 33 BLE or some other board and a SD card with Adafruit DAP library as programmer.
I had this problem with MKR Zero and I used a LPC-Link2 programmer to burn the bootloader. Once before I lost the bootloader for other reason and back then I didn't have the programmer so I used the Adafruit DAP library with an Arduino M0.

HI Juraj.  My problem is that the board is not detected by windows and only green light when i plug the usb cable. and second , I dont have ATMEL ICE or any deubgger like j-link.

@HussamMj, yes, without the bootloader the board doesn't create an USB port. you can use the Nano 33 BLE or the other SAMD board and a SD card with Adafruit DAP library as programmer

I have Seeed Wio Lite W600 which is fully  Arduino Zero Compatible and I am wondering what the possibility to use this board to burn the bootloader on the Nano 33 IOT.

@HussamMj, yes, you can use it with the AdafruitDAP library, but you will need a SD card too

I am going for the STM32 black pill.

After I waited to get my order on ebay. I managed to restore the bricked board.
The issue was related to bootloader fail. either the producer shipped it without a bootloader or some kind of static discharge caused to erase or stop the booloader from working and that why windowws didnt detect the board.
I used a converted cortex m3 to swd programmer debugger and one line cmd command.
Thank for all who contributed  solutions.
If anyone experience the same hardware failure, it is due to missing or corrupted bootloader.


text:
Help Needed! How do I attach a color sensor to a 2WD robot and use it to control its movement?
I'm relatively new to the world of Arduino, so don't be frustrated if I ask questions that could be silly. This project has a deadline, so any input is appreciated.
THE PROJECT:
I am planning to build a 2WD vehicle, with an arm using 2 servos, and a TCS3200 color sensor. The goal is to make the robot avoid obstacles while simultaneously searching for a GREEN colored object (using the color sensor). After finding the GREEN object, it would stop and use the robotic claw to grab the object. Finally, it would continue to avoid obstacles until you reach a RED colored area. It would drop the object and start again.
QUESTIONS:
That said, I have some questions about the use of different sensors to control a robot (do not hesitate to put any input that may be useful)
1) How would you connect it to the sensor shield considering the other components? Could you use analog pins or (converting digital to analog) or use fewer pins? (I just need Green and Red)
2) How would make it so that the Arduino receives data from both sensors at the same time? How can I make both sensors control the same two motors?
WIRING:

NOTE: in the second image the ultrasonic sensor should be connected to the bottom right pins
EDIT:
@Peter Paul Kiefer---Could you please elaborate on how I can achieve for both sensors to control the same motors at the same time? Link to website where it is explained?
@jsotola 1) what do you mean by output? 2) I know that, I just want for the Arduino Uno to receive data from both the Ultrasonic and color detection at the same time. Using the data, I want the Arduino to control the motors to avoid obstacles, while using the color sensor to detect the GREEN object(at the same time)
The sensor It is called a TCS3200 color sensor by the way, and seems to only use digital pins. I am connecting it to the sensor sensor shield along with other things. (refer to images in the first post)This is how it looks like:

what type of output does the color sensor use?

How can I make both sensors control the same two motors? ... the sensors do not control the motors ... the arduino controls the motors ... the sensors only provide data to the arduino

You do not need to use an "PWM"-pin. The sensor reacts on different colors by changing the frequency at the OUT pin. The S2 S3 inputs are used to specify the color your want to measure. You can use S0 and S1 to switch to different frequency ranges. Use the  pulseIn(sensorOut, LOW); function to read the LOW pulse length of the  emitted frequency to get the intensity of the light of the chosen color. You could  use the pulseIn function to read Time of Fly  for the HC-SR04 too. You can use both sensors to read the values sequentially in the loop method.

Here are some further infos: https://randomnerdtutorials.com/arduino-color-sensor-tcs230-tcs3200/ I found it by goggel the words "TCS3200" "color" "sensor".

How did you go with this? Any progress?


text:
nodemcu doesnt response in at command mode
I want to sent AT command into node mcu esp8266 module with arduino IDE  through serial monitor.
I connect the node mcu to arduino uno board in following sequence:
RX to pin 2 of arduino
TX to pin 3 of arduino
Vin of node mcu to 3.3V of arduino
GND to GND
EN of node mcu to 3.3V of arduino
I send at commands in serial monitor but dont get any response.
I also checked different baud rates.
what is the problem? what thing I'm doing wrong?
    #include <SoftwareSerial.h>
SoftwareSerial esp8266(2,3); //2 -->rx  ,3 -->tx

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

void loop() {
  if (esp8266.available()>0)
  {
      char c = esp8266.read();
      Serial.write(c);
  }
  if (Serial.available()>0)
  {
    delay(1000);
    String cmd = "";
    while (Serial.available())
    {
      cmd += (char)Serial.read();
    }
    esp8266.println(cmd);
  }
}

It is an actual NodeMCU as in a NodeMCU Version 1.0 or 0.9, etc? Not some random ESP8266 module that you're calling a NodeMCU?

@Majenko as I'm reading the board information it's model nomber is: esp-12E. I will send the image.

wire rx to tx, not rx to rx and tx to tx. do you have the AT firmware uploaded to NodeMcu? does it respond to AT commnds over USB on NodeMcu? change the baud rate to 9600 baud in firmware and sketch because SoftwareSerial doesn't work reliably at 115200 baud. why do you want to use NodeMcu this way.?

As Majenko already noted in his answer(s), the NodeMCU that you're using most probably does not come with the AT firmware installed and will not respond to AT commands out of the box. It's actually much more powerful than what you are trying to use it for.

Some points to note:

VIN should connect to 5V (it goes through the on-board 5V -> 3.3V regulator). If you connect VIN to 3.3V you will be starving the device of power.
The NodeMCU doesn't come with AT firmware installed. You will have to install it first before it will respond.
If you have a NodeMCU why are you bothering with an Arduino? The NodeMCU can do everything (and more) that the Arduino can do (except it lacks IO).

did OP do something right?


text:
NodeMCU wont connect to Blynk
My NodeMCU wont connect to Blynk with my code but works fine with example code and same auth token and WiFi info. Cant figure out why its not working. Must be something in my code interfering with it (Or something stupid I'm missing). Any ideas? Thanks!
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "AUTH";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "SSID";
char pass[] = "PASSWD";

const int analogPin = A0;

const int muxA = 9;// MUX pin A
const int muxB = 10;//MUX pin B
const int muxC = 16;//MUX pin C

const int outputPin0 = 4;// output pin 0
const int outputPin1 = 5;// output pin 1
const int outputPin2 = 12;//Output pin 2
const int outputPin3 = 13;//output pin 3
const int outputPin4 = 14;//output pin 4

int startWatering0 = 1023;//start watering value 0
int startWatering1 = 1023;//start watering value 1
int startWatering2 = 1023;//start watering value 2
int startWatering3 = 1023;//start watering value 3
int startWatering4 = 1023;//start watering value 4

int currentMoisture0 = 0;//current moisture value 0
int currentMoisture1 = 0;//current moisture value 1
int currentMoisture2 = 0;//current moisture value 2
int currentMoisture3 = 0;//current mousture value 3
int currentMoisture4 = 0;//current moisture value 4

int wateringTime0 = 0;//watering time 0
int wateringTime1 = 0;//watering time 1
int wateringTime2 = 0;//watering time 2
int wateringTime3 = 0;//watering time 3
int wateringTime4 = 0;//watering time 4

bool isWatering0 = false;//is 0 currently watering
bool isWatering1 = false;//is 1 currently watering
bool isWatering2 = false;//is 2 currently watering
bool isWatering3 = false;//is 3 currently watering
bool isWatering4 = false;//is 4 currently watering

long wateringStart0 = 0;//watering 0 start value
long wateringStart1 = 0;//watering 1 start value
long wateringStart2 = 0;//watering 2 start value
long wateringStart3 = 0;//watering 3 start value
long wateringStart4 = 0;//watering 4 start value

BlynkTimer timer;

void setup()
{
  //initialize outputs
  pinMode(muxA, OUTPUT);
  pinMode(muxB, OUTPUT);
  pinMode(muxC, OUTPUT);

  pinMode(outputPin0, OUTPUT);
  pinMode(outputPin1, OUTPUT);
  pinMode(outputPin2, OUTPUT);
  pinMode(outputPin3, OUTPUT);
  pinMode(outputPin4, OUTPUT);

  Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);

  timer.setInterval(1000L, checkSensors);
}

void checkSensors()
{
  //check sensors here
  setMux0();
  currentMoisture0 = analogRead(analogPin);
  setMux1();
  currentMoisture1 = analogRead(analogPin);
  setMux2();
  currentMoisture2 = analogRead(analogPin);
  setMux3();
  currentMoisture3 = analogRead(analogPin);
  setMux4();
  currentMoisture4 = analogRead(analogPin);
  setMux5();
  setMux6();
  setMux7();

  Blynk.virtualWrite(V11, currentMoisture0);
  Blynk.virtualWrite(V12, currentMoisture1);
  Blynk.virtualWrite(V13, currentMoisture2);
  Blynk.virtualWrite(V14, currentMoisture3);
  Blynk.virtualWrite(V15, currentMoisture4);

  //starts watering if soil is drier than set value, and if it is not already watering
  if(currentMoisture0 >= startWatering0 && isWatering0 == false)
  {
    isWatering0 = true;
    digitalWrite(outputPin0, HIGH);
    wateringStart0 = millis();
  }

  if(currentMoisture1 >= startWatering1 && isWatering1 == false)
  {
    isWatering1 = true;
    digitalWrite(outputPin1, HIGH);
    wateringStart1 = millis();
  }

  if(currentMoisture2 >= startWatering2 && isWatering3 == false)
  {
    isWatering2 = true;
    digitalWrite(outputPin2, HIGH);
    wateringStart2 = millis();
  }

  if(currentMoisture3 >= startWatering3 && isWatering3 == false)
  {
    isWatering3 = true;
    digitalWrite(outputPin3, HIGH);
    wateringStart3 = millis();
  }

  if(currentMoisture4 >= startWatering4 && isWatering4 == false)
  {
    isWatering4 = true;
    digitalWrite(outputPin4, HIGH);
    wateringStart4 = millis();
  }

///////////////////////////////////////////////////////////////////////////////////
  //stops watering if it is currently watering, and it has been watering for longer than the set time
  if(millis() >= wateringStart0 + (wateringTime0 * 60000 ) && isWatering0 == true)
  {
    isWatering0 = false;
    digitalWrite(outputPin0, LOW);
  }

  if(millis() >= wateringStart1 + (wateringTime1 * 60000 ) && isWatering1 == true)
  {
    isWatering1 = false;
    digitalWrite(outputPin1, LOW);
  }

  if(millis() >= wateringStart2 + (wateringTime2 * 60000 ) && isWatering2 == true)
  {
    isWatering2 = false;
    digitalWrite(outputPin2, LOW);
  }

  if(millis() >= wateringStart3 + (wateringTime3 * 60000 ) && isWatering3 == true)
  {
    isWatering3 = false;
    digitalWrite(outputPin3, LOW);
  }

  if(millis() >= wateringStart4 + (wateringTime4 * 60000 ) && isWatering4 == true)
  {
    isWatering4 = false;
    digitalWrite(outputPin4, LOW);
  }
}

void setMux0()//sets mux to pin 0
{
  digitalWrite(muxA, LOW);
  digitalWrite(muxB, LOW);
  digitalWrite(muxC, LOW);
}

void setMux1()//sets mux to pin 1
{
  digitalWrite(muxA, HIGH);
  digitalWrite(muxB, LOW);
  digitalWrite(muxC, LOW);
}

void setMux2()//sets mux to pin 2
{
  digitalWrite(muxA, LOW);
  digitalWrite(muxB, HIGH);
  digitalWrite(muxC, LOW);
}

void setMux3()//sets mux to pin 3
{
  digitalWrite(muxA, HIGH);
  digitalWrite(muxB, HIGH);
  digitalWrite(muxC, LOW);
}

void setMux4()//sets mux to pin 4
{
  digitalWrite(muxA, LOW);
  digitalWrite(muxB, LOW);
  digitalWrite(muxC, HIGH);
}

void setMux5()//sets mux to pin 5
{
  digitalWrite(muxA, HIGH);
  digitalWrite(muxB, LOW);
  digitalWrite(muxC, HIGH);
}

void setMux6()//sets mux to pin 6
{
  digitalWrite(muxA, LOW);
  digitalWrite(muxB, HIGH);
  digitalWrite(muxC, HIGH);
}

void setMux7()//sets mux to pin 7
{
  digitalWrite(muxA, HIGH);
  digitalWrite(muxB, HIGH);
  digitalWrite(muxC, HIGH);
}

//sets values when they are changed in app

//start watering values

BLYNK_WRITE(V1)
{
  int startWatering0 = param.asInt();
}

BLYNK_WRITE(V2)
{
  int startWatering1 = param.asInt();
}

BLYNK_WRITE(V3)
{
  int startWatering2 = param.asInt();
}

BLYNK_WRITE(V4)
{
  int startWatering3 = param.asInt();
}

BLYNK_WRITE(V5)
{
  int startWatering4 = param.asInt();
}

//watering time values

BLYNK_WRITE(V6)
{
  int wateringTime0 = param.asInt();
}

BLYNK_WRITE(V7)
{
  int wateringTime1 = param.asInt();
}

BLYNK_WRITE(V8)
{
  int wateringTime2 = param.asInt();
}

BLYNK_WRITE(V9)
{
  int wateringTime3 = param.asInt();
}

BLYNK_WRITE(V10)
{
  int wateringTime4 = param.asInt();
}

void loop()
{
  Blynk.run();
  timer.run();
}

where does it fail? ... you have no debugging code in your sketch ... please add code that prints to the serial monitor or code that blinks an LED, so that you can trace the progress of your code

In general it's not a good idea to post actual auth tokens or passwords.

I'm a bit lost with this code--for example, BLYNK_WRITE(V10) creates a local wateringTime4 and immediately returns, throwing it away. I don't think you intended to create a local variable there. The might also need to be volatile, I don't recall.

Tangentially related but the code might be a little easier to reason about if some of this data was encapsulated and shoved into an array or something.

you are brave to use pins 9 and 10. Do you have DOUT as flash mode?

@DaveNewton Whoops I meant to change those... Yeah you're right I didn't mean to create that variable, it was already created above so it could be trying to create an int thats already created causing an error or something. I will fix that and see if it works.

It is getting stuck at the pin initializing, but it gets stuck on different ones each time, sometimes 9 or 10 or 13 and even 4 once.

Ok, I figured out that it is a problem with initializing pin 9 (mux A) and it gives the following error-

wdt reset
load 0x4010f000, len 3584, room 16
tail 0
chksum 0xb0
csum 0xb0
v2843a5ac
~ld```

Ok I got it figured out, it was because I was using pin 9 and 10, I didnt know they couldn't be used. Thanks @Juraj!

I'd start by cutting it down to just the setup() and loop() functions (without the timer call) and establish whether it connects, and if not, why not.
Then add back the timer call and a very short version of checkSensors(), and try again.
Continue adding back sections of code until it fails.