delay() runs super fast unless I remove a while loop that never runs I'm working on a small game on arduino but I'm facing some really odd behavior. When I run this code all of my leds flash on and off in less than a second even though delay(10000); should stop them for 10 seconds. However if I remove the while(game_running) block they go back to flashing every 10 seconds even though that block of code never actually runs.

int yellow = 12;
int green = 10;
int red = 9;
int blue = 11;

int debug = 13;

int sequence[1000];
int level = 0;

int game_running = false;

void setup() {
  pinMode(yellow, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(red, OUTPUT);

  pinMode(debug, OUTPUT);
}

void loop() {

  // Pre Game light flash
  digitalWrite(yellow, HIGH);
  digitalWrite(green, HIGH);
  digitalWrite(red, HIGH);
  digitalWrite(blue, HIGH);
  digitalWrite(debug,HIGH);
  delay(10000);
  digitalWrite(debug,LOW);
  digitalWrite(yellow, LOW);
  digitalWrite(green, LOW);
  digitalWrite(red, LOW);
  digitalWrite(blue, LOW);
  delay(10000);

  game_running = false;
  level = 0;

  while(game_running) {

    sequence[level] = random(4); // Select next color

    // Blink LEDs
    for (int i=0; i < level; i++) {

       if(sequence[i] == 0) {
         digitalWrite(yellow, HIGH);
         delay(1000);
         digitalWrite(yellow, LOW);
         delay(1000);
       } else if(sequence[i] == 1) {
         digitalWrite(green, HIGH);
         delay(1000);
         digitalWrite(green, LOW);
         delay(1000);
       } else if(sequence[i] == 2) {
         digitalWrite(red, HIGH);
         delay(1000);
         digitalWrite(red, LOW);
         delay(1000);
       } else {
         digitalWrite(blue, HIGH);
         delay(1000);
         digitalWrite(blue, LOW);
         delay(1000);
       }
    }
    level += 1;
  }
}

I will add an official answer just so that others can see it if they run into similar problems.

The issue is with the int sequence[1000] array, which eats up 2,000 bytes of data memory. The Uno only has 2,048 bytes of data memory so the instability is due to this memory hog of an array. Use a smaller number of array entries or switch to char (if you can) to use half the bytes of an int.


Problem in Uploading a Bootloader to Atmega8A I am getting an error while Uploading the Bootloader to Atmega8A
I am selecting..

  Board -> Arduino NG and Older
  Processor -> Atmega8A
  Programmer -> USBasp

and sketch code is ArduinoISP, After selecting port then I do "Burn Bootloader"

But getting an error of...

   "efuse" memory type not defined for part "ATmega8"
    Error while burning bootloader.

Please tell me what to do. Any help will be appreciated.

Thank you

Google is your friend!!!
Apparently this is a known regression bug not yet corrected. The possible solution is also suggested there by user rigelinorion and here is the quote:

Hello, I solved it this way...

Open for edit the file C:\Program Files\Arduino\hardware\arduino\avr\platforms.txt
this is standard section uploader/programmers tools

#==============================================================================
tools.avrdude.cmd.path={runtime.ide.path}/hardware/tools/avr/bin/avrdude
tools.avrdude.config.path={runtime.ide.path}/hardware/tools/avr/etc/avrdude.conf
tools.avrdude.cmd.path.linux={runtime.ide.path}/hardware/tools/avrdude
tools.avrdude.config.path.linux={runtime.ide.path}/hardware/tools/avrdude.conf

tools.avrdude.upload.params.verbose=-v -v -v -v
tools.avrdude.upload.params.quiet=-q -q
tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude.program.params.verbose=-v -v -v -v
tools.avrdude.program.params.quiet=-q -q
tools.avrdude.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude.erase.params.verbose=-v -v -v -v
tools.avrdude.erase.params.quiet=-q -q
tools.avrdude.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} {program.extra_params} -e -Uefuse:w:{bootloader.extended_fuses}:m -Ulock:w:{bootloader.unlock_bits}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m

tools.avrdude.bootloader.params.verbose=-v -v -v -v
tools.avrdude.bootloader.params.quiet=-q -q
tools.avrdude.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{runtime.ide.path}/hardware/arduino/avr/bootloaders/{bootloader.file}:i" -Ulock:w:{bootloader.lock_bits}:m
#==============================================================================

create a new tool called, for example, avrdude1
simply copy section tools.avrdude and name it tools.avrdude1
the trick is that we remove switch "-Uefuse:w:{bootloader.extended_fuses}:m" from "tools.avrdude1.erase.pattern="

#=============================================================================
tools.avrdude1.cmd.path={runtime.ide.path}/hardware/tools/avr/bin/avrdude
tools.avrdude1.config.path={runtime.ide.path}/hardware/tools/avr/etc/avrdude.conf
tools.avrdude1.cmd.path.linux={runtime.ide.path}/hardware/tools/avrdude
tools.avrdude1.config.path.linux={runtime.ide.path}/hardware/tools/avrdude.conf

tools.avrdude1.upload.params.verbose=-v -v -v -v
tools.avrdude1.upload.params.quiet=-q -q
tools.avrdude1.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude1.program.params.verbose=-v -v -v -v
tools.avrdude1.program.params.quiet=-q -q
tools.avrdude1.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

tools.avrdude1.erase.params.verbose=-v -v -v -v
tools.avrdude1.erase.params.quiet=-q -q

#this line was edited
tools.avrdude1.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} {program.extra_params} -e -Ulock:w:{bootloader.unlock_bits}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m

tools.avrdude1.bootloader.params.verbose=-v -v -v -v
tools.avrdude1.bootloader.params.quiet=-q -q
tools.avrdude1.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{runtime.ide.path}/hardware/arduino/avr/bootloaders/{bootloader.file}:i" -Ulock:w:{bootloader.lock_bits}:m
#==============================================================================

Here is an example of the use of the tool avrdude1 in boards.txt file

atmega8.name=ATmega8 OPTIBOOT
atmega8.upload.protocol=arduino
atmega8.upload.maximum_size=7168
atmega8.upload.speed=115200
atmega8.upload.tool=avrdude1
atmega8.bootloader.low_fuses=0xbf
atmega8.bootloader.high_fuses=0xCC
atmega8.bootloader.path=atmega8
atmega8.bootloader.file=optiboot/optiboot_atmega8.hex
atmega8.bootloader.unlock_bits=0x3F
atmega8.bootloader.lock_bits=0x0F
atmega8.bootloader.tool=avrdude1
atmega8.build.mcu=atmega8
atmega8.build.f_cpu=16000000L
atmega8.build.core=arduino
atmega8.build.variant=standard


Help reading orientation from gyroscope I recently bought a L3GD20H Triple-Axis Gyro to use it to measure orientation, but found out it instead reports the rate of rotation in degrees per second. I was told this means that to detect the total degrees of rotation, I need to integrate the rate of rotation over time.
I was wondering if someone could help me with this since I'm having trouble wrapping my head around a formula to create. here is my code so far if it helps:

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_L3GD20_U.h>

/* Assign a unique ID to this sensor at the same time */
Adafruit_L3GD20_Unified gyro = Adafruit_L3GD20_Unified(20);

void displaySensorDetails(void)
{
  sensor_t sensor;
  gyro.getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" rad/s");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" rad/s");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" rad/s");
  Serial.println("------------------------------------");
  Serial.println("");
  delay(500);
}

void setup(void)
{
  Serial.begin(9600);
  Serial.println("Gyroscope Test"); Serial.println("");

  /* Enable auto-ranging */
  gyro.enableAutoRange(true);

  /* Initialise the sensor */
  if(!gyro.begin())
  {
    /* There was a problem detecting the L3GD20 ... check your connections */
    Serial.println("Ooops, no L3GD20 detected ... Check your wiring!");
    while(1);
  }

  /* Display some basic information on this sensor */
  displaySensorDetails();
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  gyro.getEvent(&event);

  /* Display the results (speed is measured in rad/s) */
  Serial.print("X: "); Serial.print(event.gyro.x); Serial.print("  ");
  Serial.print("Y: "); Serial.print(event.gyro.y); Serial.print("  ");
  Serial.print("Z: "); Serial.print(event.gyro.z); Serial.print("  ");
  Serial.println("rad/s ");
  delay(1);
}

So in summary, I need help creating the code/a formula that will use my Gyro to measure its orientation. Thank you for your time! I'm very lost.

Take a look at this example.

#include <Wire.h>

const int MPU = 0x68; // MPU6050 I2C address
float AccX, AccY, AccZ;
float GyroX, GyroY, GyroZ;
float accAngleX, accAngleY, gyroAngleX, gyroAngleY, gyroAngleZ;
float roll, pitch, yaw;
float AccErrorX, AccErrorY, GyroErrorX, GyroErrorY, GyroErrorZ;
float elapsedTime, currentTime, previousTime;
int c = 0;

void setup() {
  Serial.begin(19200);
  Wire.begin();                      // Initialize comunication
  Wire.beginTransmission(MPU);       // Start communication with MPU6050 // MPU=0x68
  Wire.write(0x6B);                  // Talk to the register 6B
  Wire.write(0x00);                  // Make reset - place a 0 into the 6B register
  Wire.endTransmission(true);        //end the transmission
  /*
  // Configure Accelerometer Sensitivity - Full Scale Range (default +/- 2g)
  Wire.beginTransmission(MPU);
  Wire.write(0x1C);                  //Talk to the ACCEL_CONFIG register (1C hex)
  Wire.write(0x10);                  //Set the register bits as 00010000 (+/- 8g full scale range)
  Wire.endTransmission(true);
  // Configure Gyro Sensitivity - Full Scale Range (default +/- 250deg/s)
  Wire.beginTransmission(MPU);
  Wire.write(0x1B);                   // Talk to the GYRO_CONFIG register (1B hex)
  Wire.write(0x10);                   // Set the register bits as 00010000 (1000deg/s full scale)
  Wire.endTransmission(true);
  delay(20);
  */
  // Call this function if you need to get the IMU error values for your module
  calculate_IMU_error();
  delay(20);

}

void loop() {
  // === Read acceleromter data === //
  Wire.beginTransmission(MPU);
  Wire.write(0x3B); // Start with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 6 registers total, each axis value is stored in 2 registers
  //For a range of +-2g, we need to divide the raw values by 16384, according to the datasheet
  AccX = (Wire.read() << 8 | Wire.read()) / 16384.0; // X-axis value
  AccY = (Wire.read() << 8 | Wire.read()) / 16384.0; // Y-axis value
  AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0; // Z-axis value
  // Calculating Roll and Pitch from the accelerometer data
  accAngleX = (atan(AccY / sqrt(pow(AccX, 2) + pow(AccZ, 2))) * 180 / PI) - 0.58; // AccErrorX ~(0.58) See the calculate_IMU_error()custom function for more details
  accAngleY = (atan(-1 * AccX / sqrt(pow(AccY, 2) + pow(AccZ, 2))) * 180 / PI) + 1.58; // AccErrorY ~(-1.58)

  // === Read gyroscope data === //
  previousTime = currentTime;        // Previous time is stored before the actual time read
  currentTime = millis();            // Current time actual time read
  elapsedTime = (currentTime - previousTime) / 1000; // Divide by 1000 to get seconds
  Wire.beginTransmission(MPU);
  Wire.write(0x43); // Gyro data first register address 0x43
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 4 registers total, each axis value is stored in 2 registers
  GyroX = (Wire.read() << 8 | Wire.read()) / 131.0; // For a 250deg/s range we have to divide first the raw value by 131.0, according to the datasheet
  GyroY = (Wire.read() << 8 | Wire.read()) / 131.0;
  GyroZ = (Wire.read() << 8 | Wire.read()) / 131.0;
  // Correct the outputs with the calculated error values
  GyroX = GyroX + 0.56; // GyroErrorX ~(-0.56)
  GyroY = GyroY - 2; // GyroErrorY ~(2)
  GyroZ = GyroZ + 0.79; // GyroErrorZ ~ (-0.8)

  // Currently the raw values are in degrees per seconds, deg/s, so we need to multiply by sendonds (s) to get the angle in degrees
  gyroAngleX = gyroAngleX + GyroX * elapsedTime; // deg/s * s = deg
  gyroAngleY = gyroAngleY + GyroY * elapsedTime;
  yaw =  yaw + GyroZ * elapsedTime;

  // Complementary filter - combine acceleromter and gyro angle values
  roll = 0.96 * gyroAngleX + 0.04 * accAngleX;
  pitch = 0.96 * gyroAngleY + 0.04 * accAngleY;

  // Print the values on the serial monitor
  Serial.print(roll);
  Serial.print("/");
  Serial.print(pitch);
  Serial.print("/");
  Serial.println(yaw);
}

void calculate_IMU_error() {
  // We can call this funtion in the setup section to calculate the accelerometer and gyro data error. From here we will get the error values used in the above equations printed on the Serial Monitor.
  // Note that we should place the IMU flat in order to get the proper values, so that we then can the correct values
  // Read accelerometer values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    AccX = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccY = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    // Sum all readings
    AccErrorX = AccErrorX + ((atan((AccY) / sqrt(pow((AccX), 2) + pow((AccZ), 2))) * 180 / PI));
    AccErrorY = AccErrorY + ((atan(-1 * (AccX) / sqrt(pow((AccY), 2) + pow((AccZ), 2))) * 180 / PI));
    c++;
  }
  //Divide the sum by 200 to get the error value
  AccErrorX = AccErrorX / 200;
  AccErrorY = AccErrorY / 200;
  c = 0;
  // Read gyro values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x43);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    GyroX = Wire.read() << 8 | Wire.read();
    GyroY = Wire.read() << 8 | Wire.read();
    GyroZ = Wire.read() << 8 | Wire.read();
    // Sum all readings
    GyroErrorX = GyroErrorX + (GyroX / 131.0);
    GyroErrorY = GyroErrorY + (GyroY / 131.0);
    GyroErrorZ = GyroErrorZ + (GyroZ / 131.0);
    c++;
  }
  //Divide the sum by 200 to get the error value
  GyroErrorX = GyroErrorX / 200;
  GyroErrorY = GyroErrorY / 200;
  GyroErrorZ = GyroErrorZ / 200;
  // Print the error values on the Serial Monitor
  Serial.print("AccErrorX: ");
  Serial.println(AccErrorX);
  Serial.print("AccErrorY: ");
  Serial.println(AccErrorY);
  Serial.print("GyroErrorX: ");
  Serial.println(GyroErrorX);
  Serial.print("GyroErrorY: ");
  Serial.println(GyroErrorY);
  Serial.print("GyroErrorZ: ");
  Serial.println(GyroErrorZ);
}

https://howtomechatronics.com/tutorials/arduino/arduino-and-mpu6050-accelerometer-and-gyroscope-tutorial/


What if Ultrasonic sensor doesn't detect object? I am trying to write a sketch where a function will only be triggered when the ultrasound doesn't return back. Thus when the echo pin is checked after 1 second after the trigger pin was written high, it must be low. Will it be a digitalRead function?

What type of Ultrasonic sensor do you have?

I'll go with HC-SR04, since I've got one of those laying around here. The other ultrasonic sensors should be working in the same way.

Before you start!

Read the datasheet. A fast search on google with: "[manufacturer][device id][device description] datasheet .pdf" will do good.

Example: http://www.micropik.com/PDF/HCSR04.pdf

The datasheet will tell you important things/values and sometimes even interfacing examples or code.
Like:

Max input voltage
Max current
Pin-out diagrams
How to interface with the device
Min/max operating temperature

Wiring up

The datasheet will tell you what to connect, to which pins.

We've got 5V, Trigger (input), Echo (output), 0V (ground).

(As per datasheet)

It's best to do the wiring before you put power on it, because you can accidently short it when moving wires around.

Interfacing

I would recommend checking some code examples before you attempt to roll your own. Or just start from an example and edit it to your specifications.

The timing diagram shows us it needs a 10uS pulse on the trigger input.
And the duration of the echo will show the distance (58 uS per cm or 148 uS per inch).

The datasheet also suggest to use over 60ms measurement cycles.

Code

Taking all that into account:

#define trigPin 13
#define echoPin 12
#define led 11
#define led2 10

const unsigned long timeout = 400*58; //Max of 400CM, adjust this to your own max.

void setup() {
  Serial.begin(115200);//Stop using 9600 as default, it's not fast.
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
}

void loop() {
  unsigned long distance;//unsigned, since we don't get negative distances.
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); //10 uS pulse.
  digitalWrite(trigPin, LOW);

  distance = round(pulseIn(echoPin, HIGH,timeout) /58);//Distance in CM's, use /148 for inches.
  if (distance == 0){//Reached timeout
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(60);//Wait 60 ms for next cycle.
}

To be honest, I'm not even slightly sure if this code is working.
I modified this code: http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/

So that you're actually using the timeout right, and do the timing according to the datasheet.


Why does my code or Serial Monitor hang with analogRead? I have the following code in loop() to collect values from an electret microphone

for(int i=0; i<sampleSize; i++){
  analogVal[i]= analogRead(ADC_Pin);
  sumOfSquares= sumOfSquares+sq(analogVal[i]);
}
Serial.print("Sum of squares: ");
Serial.print(sumOfSquares);

where sampleSize is an int variable, I've tried numbers from 3 to 1000, which is my desired value. ADC_Pin is an int variable set to be A1 and has been properly initialized through pinMode. analogVal is an int array of size sampleSize.

My circuit appears to be fine because the output produces a reasonable amount of voltage. I've tried eliminating the line with sumOfSquares and just having the first line in the for loop. However, the Serial Monitor hangs and does not display any values. The serial communication is at 9600 bps.

Arduino UNO have 2K RAM (many other too). That is 2048 bytes of RAM.

I suppose, that analogVals[] is declared as int and having 1000 entries it takes 2000 bytes of RAM, leaving wholesome 48 bytes for all your others variables (including int i in the for cycle and Serial outside it) and stack for calling functions (like analogRead and sq) and all theirs variables and functions and arguments.

So int i = 2B, Serial = 2B, sumOfSquares = 2B, "Sum of squares: " = 17B of what I see takes anothe 23 bytes of those 48 bytes leaving us with only 25 bytes for all else.

I bet, that you try to use more REAM, than you have and so your stack overflows and

destroys some variable content on the vay
is overwriten by assigning to some variables, which then leads to all sort of problems.


My Arduino smokes every time I connect an AC/DC wall adapter to it. Can someone help me to fix it? I copied the schematic below and when I ran the code from my laptop, it worked well but every time I unplug it to my laptop and connect an ac dc wall adapter, my Arduino smokes. Why does it smoke and how to fix it so that I can connect an AC/DC wall adapter to power my Arduino? EDIT from the comments: My AC/DC adapter has 19.5V DC out.

As already stated in the comments, the voltage of your power supply is the problem. The Arduino has a linear voltage regulator at the Vin pin. It dissipates the excess voltage as heat. The higher the supplied voltage, the lower the current, that you can draw before it overheats. The regulator on a genuine Arduino should go into thermal shutdown, while the regulators on most cheap clones will just get destroyed.

19.5V is too high for the Arduino. The Vin pin is meant for  6 to 12V max. You need a power supply, that can provide a voltage in that range. Or you can buy a regulated power supply, that directly gives you the 5V, that the Arduino needs.

Also you should be really carefull with powering the motor through the Arduinos 5V pin. Motors can easily draw a big amount of current. When drawing too much current through the Arduino (to be specific: through the voltage regulator or the protection diode), the same as explained above will happen. Only very small motors can be supplied through the Arduino. As you use a relay to control it, I guess the motor draws a lot of current. You need tp connect it directly to a fitting power supply, so that the current for it does not flow through the Arduino.

And always be sure, that the used parts can work with the voltage, that you want to supply, including the motor.


How Bootload an Lilypad Arduino USB using Arduino UNO I recently bought two lilypads USB, one works perfectly (it's recognized in my computer, but the other one it's never recognized, I even try in different computers and the same scenario with both devices)

So I think that maybe the second one doesn't have a bootloader installed. So I'm triying to "burn" a new bootloader. I have been triying following the guide on https://www.arduino.cc/en/Tutorial/ArduinoISP using as programmer an Arduino UNO but without luck. I ever get avrdude: Device signature = 0x000000 (retrying). Thanks for the help!

If you try uploading to a LilyPad USB with the wrong board selected, you may end up in a condition where the bootloader can no longer respond normally.

You can get the LilyPad Arduino into bootloader mode by tapping the reset button twice in under a second. Once in bootloader mode, the LED should blink at about 1Hz for about 8 seconds. My advice is to load a blank sketch (i.e., nothing in loop() or setup()) and then double tap the reset button shortly after hitting the upload button. That should restore the LilyPad USB to a working state.


Arduino Micro + Max4466 - Noise on A0 I've got an Arduino Micro, and a MAX4466 ECM / AMP breakout board (https://www.adafruit.com/product/1063). I'm powering the Arduino Micro from the USB port.

On the MAX4466 (to the Arduino), I've wired VCC to 3.3v, GND to GND, and OUT to A0. I've also wired 3.3v to AREF.

Using the following code, I'm noticing significant noise spikes on the output, as shown in the graph below.

I'm not entirely sure what I've done wrong here, and would appreciate any input / criticism that could lead to getting a clean signal.

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

void loop()
{
   Serial.println(analogRead(0));
}

The OP itself solve it:

  Ok - so I suspected that it was the Arduino at fault.. Turns out it's
  a cheap Chinese clone. After purchasing an official Micro, and wiring
  up the same component, I'm getting a nice clean signal (bar a small
  amount of acceptable noise), which is reflecting input tones
  accurately. Thanks again for all the input!


Arduino sensing its 'Motion' I am working on a project where I need the Arduino to 'sense' at what direction its moving. For example, I want the Arduino to 'sense' that it
is moving towards 'forward' direction, 'backwards' direction etc.

Is that possible using an Arduino? Can I use a motion sensor to do this (probably not)?

Can any one please help me to find the right 'direction'?

For this you need a acceleration/gyro sensor, like the MPU6050.

By tracking x/y/z movements, you can define what is forward/backards etc. Also you can track angles/tilts (in 3 directions).

See an example how to use it here: MPU-6050


Problem with programming an ATtiny85: Error - avrdude: Yikes! Invalid device signature I'm trying to program an Attiny85 chip using an Arduino Uno as an ISP following this two tutorials: Instructables: Program an ATtiny With Arduino and Programming an ATtiny w/ Arduino 1.6 (or 1.0) but every time I try to upload the sketch I get this error message:

     avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

I have tried different Arduino boards/changing port and different ATtiny chips but the results are all the same. I have also checked the wiring multiple times and it seems to be correct.

This is the full error message (on verbose mode):

     avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM7
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATtiny85
     Chip Erase delay              : 400000 us
     PAGEL                         : P00
     BS2                           : P00
     RESET disposition             : possible i/o
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    12     4    0 no        512    4      0  4000  4500 0xff 0xff
       flash         65     6    32    0 yes      8192   64    128 30000 30000 0xff 0xff
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          2    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

     avrdude: AVR device initialized and ready to accept instructions

     Reading | ################################################## | 100% 0.05s

     avrdude: Device signature = 0x000000 (retrying)

     Reading | ################################################## | 100% 0.05s

     avrdude: Device signature = 0x000000 (retrying)

     Reading | ################################################## | 100% 0.05s

     avrdude: Device signature = 0x000000
     avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

     avrdude done.  Thank you.

Try connecting the RESET pin of the Attiny85 to GND the second before you hit "program".

In my experience, the Arduino does not always send the RESET signal when it should (or on the pin that you think it would send it).

In these cases, manually resetting the Attiny by connecting the RESET pin to ground makes it programmable.

You can keep RESET low during the whole programming process, but if you keep it low for many minutes before programming the chip, it might not always work. In those cases, set RESET high for a moment before setting it back low, and the Attiny should be good for another round of programming.

And of course, when you want the Attiny to start doing what you have programmed it to do, you have to pull RESET high again.


ESP8266 not sending temperature data to text message i am trying to use a ESP8266 module to send temperature data using twilio and send it to my phone via text message. However it does not send the sensor data but the text i placed. Is it possible if i can get it to send sensor data instead? If so how can i do this?

strcat(data,"From=");
    strcat(data,PHONE_FROM);
    strcat(data,"&");

    strcat(data,"To=");
    strcat(data,PHONE_TO);
    strcat(data,"&");

    strcat(data,"sid=");
    strcat(data,TWILIO_ACCOUNT_SID);
    strcat(data,"&");

    strcat(data,"token=");
    strcat(data,TWILIO_TOKEN);
    strcat(data,"&");

    strcat(data,"Body=");
    const char TEXT_MESSAGE_BODY []  = "temperature", temperature;
    strcat(data,TEXT_MESSAGE_BODY);

    wifi.httpPost("iot-https-relay.appspot.com","/twilio/Messages.json",data);

temperature should be getting sensor raw data and paste it after the "temperature" but it is not working.

Not 100% sure what you are trying to do with the line:

const char TEXT_MESSAGE_BODY []  = "temperature", temperature;

This will not assign the value in temperature to TEXT_MESSAGE_BODY, it will create a variable of type char called temperature.

You will need to get your temperature value into a string (array of char) using sprintf() or similar to convert from the base type (float, double?).

Replace const TEXT_MESSAGE_BODY [] ... etc with :

strcat(data,"temperature");

char temperature_s[20];
sprintf(temperature_s, "%f", rawTemperature);
strcat(data,temperature_s);

Above assumes rawTemperature is a float holding the value read from the sensor, but the same idea applies for other data types..  There is no checking for buffer overflow etc, but you get the idea.


l293d is not able to drive two 300 rpm motors simultaneously I am using l293d in a line follower but recently I am facing a problem. my l293d motor driver is not able to power 2 300 rpm motors simultaneously while with one of the motors at a time it works perfectly fine. Earlier it used to drive both the motors at optimal desired speed but recently its posing the above mentioned problems. I have tried replacing the Motor driver and Arduino itself but nothing worked and I am still facing the problem.

Check if both channels are working in either direction individually.
Check the current draw under the load per motor using an Digital Multimeter as an Ammeter function.

The L293 is designed to provide bidirectional drive currents of up to 1A at voltages from 4.5V to 36V.
600mA per channel for L293D

As long as your motors at drawing more than 600mA per motor, it should work fine.


Arduino + nRF24L01 + ESP8266 mod I was wondering if it is possible to connecting two Arduino boards with each other (Uno + Nano) using an ESP8266 mod on one of them and an nRF24L01 on the other board?

I have seen lots of details of connecting two nRF but couldn't find any about ESP talking to nRF.

No. That would be like trying to connect your TV to your microwave. Both RF devices, but both work different ways and do different things.

Just because they are both rectangular boxes with a window in the front doesn't mean they are the same.


util/delay.h from arduino _delay_ms not delaying in accurate time with my hardware configuration I have configured my arduino as a flash programmer and i'm sending data to an atmega328P. It is actually working and the data is send to my atmega328. But what is strange that the _delay_ms from  from the Arduino library is not delaying in accurate seconds.

_delay_ms(1000) who should wait from 1s, is actually more 8 seconds from my atmega328P hardware point of view.

My question is what could possibly turn the program wrong. I'm strongly assuming that this a misconfigured clock cycle from my Atmega, but this is my newbie guess,  it can be something else, that's why I'm posting my question here. Can someone can hint me what's wrong with my configuration?

Here's the sample code, a dumb toggle pin on / off:

#include <util/delay.h> // from arduino library

/*
*/

 DDRB |= 0b0000001;

  while (1) {
    PORTB = 0b00000001;
    _delay_ms(1000); // it should be 1 second, but on my hardware it is more ~8 seconds

    PORTB = 0b00000000;
    _delay_ms(1000);
  }

And my configuration is (from arduino IDE)

Arduino Pro / pro Mini (3,3v 8 Mhz) / Atmega 328

I have tried with

Arduino Pro / pro Mini (5v 16 Mhz) / Atmega 328

expecting that more power will affect speed, but the result is actually the same.

At a 30000 ft. level, it's because the defined F_CPU value doesn't match your hardware. This can happen because the incorrect device is chosen in the IDE or because the device is misconfigured in boards.txt, or because the hardware is somehow different from what is expected.

Given that you are using a bare ATmega328P, assuming that you've selected the correct crystal, and that the apparent time scale is 8x, it is likely that the CKDIV8 fuse is set. This means that the chip is running at 1/8 the crystal speed. You will need to unprogram (set to 1) bit 7 of the low fuse byte in order to reset it. Use AVRdude from the command line to read the low fuse byte (-U lfuse:r:-:h), set the bit (lfuse | 0x80), and then write it back (-U lfuse:w:0xnn:m).


Can SoftwareSerial be used in an ESP01 I am using ESP01 as a microcontroller that retrieves information from Firebase and sends them over serial to an Arduino Uno for other uses. I am not using NODEMcu since it has few analog pins and ESP01 is the only option available for me at this time.
Can the GPIO 0 and GPIO 2 pins available in the ESP01 be used as a serial communication pins when defined with SoftwareSerial library?
I want to keep the serial from the existing TX and RX for debugging and testing.

Check your other post I answered it there. The ESP01 has 2 serial channels.


How to determine the SPIFFS size on an esp8266-01? I'm confused about my esp8266-01 if they have SPIFFS or not. Is there a way to find it out? If they have, how to get their size?

I've got the following flash id: 0x1440e0.

Example SPIFFS apps keep crashing with wdt reset and lots of dumped hexes.

First you need to know the size of the flash memory attached to esp8266 on your module. Common sizes are 512 kB (4Mbit), 1 MB (8Mbit) and 4 MB. Espressif Flash Download Tool (Windows) or esptool can determine it.

You can choose the size of the SPIFFS in your flash 'layout' by selecting the option in IDE Tools menu. Take one according to for you flash size and size of the files you want to put into SPIFFS.

If you have 1 MB flash on your module and you want to use OTA upload, let flash space for twice a space taken by the sketch.


String to unsigned long conversion I'm trying to use strtoul() to convert an Arduino String to an unsigned long (like the return of millis();) using the following code snippet:

unsigned long foo (String time)
{
  unsigned long mili;
  char Tim[9]="";
  uint16_t timsize = time.length()+1;
  char TIM[timsize];
  time.toCharArray(TIM,timsize);
  mili=strtoul(TIM,timsize,10);
  return mili;
}

The code seems to work. However, I'm getting the following warning:

  invalid conversion from 'uint16_t {aka unsigned int}' to 'char**' [-fpermissive] mili=strtoul(TIM,timsize,10);

My question is twofold:

Is there a better way to convert a String to unsigned long without first converting to a C string?
If not, how can I eliminate this error?

Arduino String class provides method c_str(). So you don't have to convert it to C string, as it's already stored as a C string internally.

And as mentioned in comments, the second parameter of strtoul is:

  endptr
      Reference to an object of type char*, whose value is set by the function to the next character in str after the numerical value.
      This parameter can also be a null pointer, in which case it is not used.

Basically you can reduce whole foo to the:  return strtoul(time.c_str(), NULL, 10);


Porting "far" flash memory access from Arduino Mega to Due I have a project that runs on the Arduino Mega 2560 which takes up almost the complete amount of flash memory available (https://github.com/fredlcore/bsb_lan/blob/master/BSB_lan.ino). Because of this, I'm planning on migrating the project to the Arduino Due.

My main problem at the moment is to port those functions that access flash memory in the "far" memory area (>64k) for which on the one hand various _PF functions (like strncpy_PF) are provided, and on the other hand a dummy "pointer" type uint_farptr_t (which is actually uint32_t) is available.

My problems now are twofold:

While the _PF functions have specific definements for the Due which under "normal" circumstances should work without changes in the code, they expect different variable types. For example, strncpy_PF takes uint_farptr_t (i.e. uint32_t) as argument for src on the Mega, it expects a const char * on the Due. Compilation thus results in lots of errors.
For the Mega to be able to access char arrays (which are 16 Bit on the Mega) above 128k, I need a rather dirty workaround (see function calc_enum_offset() in the code linked above). Basically I need to take the memory address of a 16 Bit char pointer and make some calculations to get the final address from which I read the strings. On the Mega, I can do these calculations on the basis of uint_farptr_t and then read from the calculated memory address with pgm_read_byte_far() for example. On the Due, however, pgm_read_byte_far(addr) is translated to (*(const unsigned char *)(addr)). Again, the uint32_t type does not fit this.

Do you have any suggestions on how I should tackle these issues with the least amount of code?

The Due, being ARM, is a von Neumann architecture. That means that it has no concept of "progmem", "near" or "far" pointers, etc.  There are no _P or _PF variant functions, but the Arduino core provides simple stubs as a convenience.

Instead all "flash" memory access is just simple memory accesses using const.

The best thing you can do is to use preprocessor macros to select between AVR and ARM code:

#if defined(__AVR__)
    strncpy_PF(buffer, enumstr+c, sizeof(buffer));
    buffer[sizeof(buffer)-1] = 0;
    outBufLen+=sprintf(outBuf+outBufLen,"%d - %s",val,buffer);
#else
    outBufLen += sprintf(outBuf + oufBufLen, "%d - %s", val, cmdtbl[i].enumstr);
#endif

In fact, given the huge amount of "hackiness" involved in that program with regards the cmdtbl, and the massive amounts of code that just aren't needed on the Due, it may be better to start a fresh program that is Due specific and delete the swathes of unneeded code.


powering the arduino uno I need to power an arduino uno with a battery but for a very long period of time. And I read a lot of thing about this. Some say do not use a 9V battery with a regulator some other say that it is the best way. SO I am really confused and I need to know what's the best solution for this (taking into consideration the fact that I need my board to last a week at least, if it is possible?)

Thanks!

The Arduino Uno is not really designed for that. Simply keeping the power indicator LED, regulators and extra circuits on for a week will require in the order of 1500-2000 mAh (10*24*7=1680mAh). That is without any application at all on the MCU.

Now it is possible to modify the board and reduce this extra power requirements to less than 1 mA and as low as 0.1 mA. Or even better buy a Pro Mini clone and cut the wiring to the LED and regulator, and power with a 3.7 V/1500mAh battery directly.

Here is a great reference on the subject.

Cheers!


How to pass 2 parameters with RCSwitch library? I'm learning Arduino's world, but knowing very little about C and C++.

I'm trying to achieve a little RF transmitter which should send the temperature and  humidity from a DHT-11 sensor to a Raspberry Pi.

I'm using the RCSwitch library to send information with the Arduino, and the 433Utils library to receive it on the RPI.

Using those 2 libraries demos, I was able to send an integer, holding temperature or humidity information (mySwitch.send("00001010");), and read it on the RPI.

But how can I send both informations so that the RPI will know which one is the temperature and the humidity ?

I know I could just send both and assume the lowest is the temperature, but this would be very messy and not very rewarding.

EDIT :

Following Edgar's answer in https://arduino.stackexchange.com/a/52992/11604, I know write:

void send_string(const char *str){
    int i = 0;
    for (char *p = str; *p; p++ ) {
        mySwitch.send((i<<8) + *p, 16);
        i++;
    }
}

void loop() {
    delay(1000);
    h=40.650;
    t=32.0078;
    hic=33.586;
    String x = "$H" + String(h) + "T" + String(t) + "HI" + String(hic);
    send_string(x.c_str());
}

Works perfectly ! (see his complete answer for the RPI-side code)

The library you have chosen is not designed for transmitting information between nodes. It is intended for sending simple ON/OFF commands to RF-connected switches.  Bending it to send data in the way you want would be difficult.  Not impossible, but difficult.

Instead you should be considering a more suitable system, such as the popular RadioHead library. It appears to have Raspberry Pi support out of the box:

  Raspberry Pi Uses BCM2835 library for GPIO http://www.airspayce.com/mikem/bcm2835/ Currently works only with RH_NRF24 driver or other drivers that do not require interrupt support. Contributed by Mike Poublon.

Alternatively a small Arduino as an interface between the RF module and the Pi may be another option.


Unable to connect Arduino Uno to Ubuntu 16.04 I've received an Arduino Uno today only. I have zero experience prior to Arduino boards or any other micro controller. I followed every step very carefully from the setting up guide for Linux based OS, but I still can't connect the board with my Ubuntu 16.04 PC. After googling the problem I found that the device must show up as ttyACM* but I don't see any such device in /dev. Its also not listed under the command lsusb but the LED's on the board are working properly. The ON LED is turned on when I connect it with my PC and the inbuilt LED starts to blink.

This is what the IDE displays:

You may have to add yourself to the dialout group in Ubuntu so that your user account can access the serial ports.

Then, in the Arduino IDE, the Tools->Port menu should show you options. Right now, the screenshot you gave shows that it's set for COM1, which is a Windows-style serial port naming and definitely won't work on Ubuntu.


WebSocket Server for MKR1000 I was looking for a websocket server for my MKR100 but nothing I found looks it works. I tried all the  libraries that come with arduino but half of those doesn't compile on MKR1000 and those that did it doesn't work at all.
Your help would be greatly appreciated!

This old and simple one has always worked for me on several Arduinos (but I haven't tried it on the MKR1000 specifically):
https://github.com/morrissinger/ESP8266-Websocket
I have forked it and made some changes, but nothing fundamental:
https://github.com/ocrdu/NINA-Websocket
Have a go, it just might work for you.


Inheritance: error in calling the constructor of the base class? I want to write a library for the RGBDigit shield (http://rgbdigit.com/), which essentially is an Adafruit Neopixel strip, packed as a 7 segment display. The shield also has a DS3231 clock and an IR receiver.

So my plan was to make a class RGBDigit, which inherits from the Adafruit_NeoPixel class and add private objects DS3231 and IRrecv.

This is my RGBDigit.h:

#ifndef RGBDigit_h
#define RGBDigit_h

#include <Arduino.h>
#include "Wire.h"
#include "../Adafruit_NeoPixel/Adafruit_NeoPixel.h"
#include "../IRremote/IRremote.h"
#include "../DS3231/DS3231.h"

class RGBDigit : public Adafruit_NeoPixel {
    public:
        RGBDigit(int nDigits);
        ~RGBDigit();
    private:
        int _nDigits;
        DS3231 _clock;
        IRrecv* _ir;
};

#endif

This is RGBDigit.cpp:

#include "RGBDigit.h"

RGBDigit::RGBDigit(int nDigits)
    : Adafruit_NeoPixel(8 * nDigits, 12, NEO_GRB + NEO_KHZ800),
    _nDigits(nDigits)
{
    _ir = new IRrecv(10);
    _ir->enableIRIn(); // Start the receiver
    Adafruit_NeoPixel::begin();
}

RGBDigit::~RGBDigit()
{
    delete _ir;
}

And this is my Arduino sketch:

#include <Wire.h>
#include <RGBDigit.h>

RGBDigit display = RGBDigit(4);

void setup() {
    // put your setup code here, to run once:

}

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

}

I get al lot of "undefined reference" errors:

RGBDigit/RGBDigit.cpp.o: In function `RGBDigit::RGBDigit(int)':
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:23: undefined reference to `Adafruit_NeoPixel::Adafruit_NeoPixel(unsigned int, unsigned char, unsigned char)'
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:23: undefined reference to `DS3231::DS3231()'
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:25: undefined reference to `IRrecv::IRrecv(int)'
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:26: undefined reference to `IRrecv::enableIRIn()'
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:27: undefined reference to `Adafruit_NeoPixel::begin()'
RGBDigit/RGBDigit.cpp.o: In function `RGBDigit::~RGBDigit()':
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:30: undefined reference to `Adafruit_NeoPixel::~Adafruit_NeoPixel()'
collect2: error: ld returned 1 exit status

But I don' t understand why. What am I doing wrong?

#include "../Adafruit_NeoPixel/Adafruit_NeoPixel.h"
#include "../IRremote/IRremote.h"
#include "../DS3231/DS3231.h"

What you're doing there is telling the compiler where, relative to where it's performing the compiling (or one of its include directories), the header files you list are.

What you're not doing is telling the IDE where the CPP files are to compile and link with your sketch.

When including anything external to the sketch folder that is more than just a header file you must treat it as an Arduino library - that is, place it in one of the standard library folders and name it properly (libraries should be named LibraryName/LibraryName.h).

Then you include the libraries properly:

#include <Adafruit_NeoPixel.h>
#include <IRremote.h>
#include <DS3231.h>

You must do that in both your sketch and your custom library.  That way the IDE knows where to look for the files to compile - the compiler doesn't understand the concept of an Arduino library (and thus the CPP files associated with a header file) - that is purely down to the IDE gathering the data by examining your sketch and locating the right files to then pass to the compiler.


Purpose of this resistor in Arduino Nano schematic I was looking at the Arduino Nano's schematic and noticed a resistor that seems to be pointless (RP2C on this picture).

Also there is numbers 6 and 3 on it, does it mean that resistor is connected to pins 6 and 3 on FT232 or to the same pins on Atmega328?

The resistor is one of 4 resistors that make up an SMD resistor array, RP2. It is seen on the board here:

The resistor array works like this:

The resistor on this array is spare, so both terminals are grounded.


Intermittent LOW reading from input pin set to INPUT_PULLUP i have an output pin connected to a magnetic reed switch. The pin mode is INPUT_PULLUP. When the switch is closed, it connects the pin to GND and drags the pin to a LOW reading. I check the state of the pin in the loop function. Occasionally the pin reads LOW when it shouldn't (the switch is not closed) - e.g. around once per second. What could cause this? The wire from the pin to the switch is about 1m long - could this be long enough to intermittently drag it down to a LOW? Also, it seems to happen much more when the air temperature is hotter.

Circuit summary: Pin (INPUT_PULLUP) -> Magnetic reed switch -> GND

My guess would be that you're getting noise interference on the line and it's too much for the Arduino's little internal pullup.  Try adding an external pullup resistor - say 5k-10k (exact value is not critical).


How do I read addresses on multiple DS2413 1-Wire GPIO Breakouts, using the Adafruit sketch? I am using three DS2413 1-Wire GPIO Breakouts from Adafruit connected to an ESP8266.  I tested the DS2413
 breakouts using their example sketch and it works fine for just one DS2413.  But I cannot get it to work when 2 or more DS2413s are connected.

Adafruit DS2413 Example Sketch
 https://github.com/adafruit/Adafruit_DS2413/blob/master/DS2413.pde

Adafruit DS2413 Overview
https://learn.adafruit.com/adafruit-1-wire-gpio-breakout-ds2413?view=all

When I connect 2 or more DS2413s, it only blinks the LEDs connected to the 1st breakout and doesn't read the other addresses.

I made some changes to the void setup section and now I am getting the following in the serial monitor. It sees all the addresses, but it is duplicating them and the first set have "No device found on the bus!" at the end. How can I get the sketch to read all the addresses without these errors?

Serial monitor

Looking for a DS2413 on the bus
3A B2 C2 39 00 00 00 8C No device found on the bus!
3A 8E AE 39 00 00 00 2C No device found on the bus!
3A E5 B6 39 00 00 00 55 No device found on the bus!
Found a DS2413: 3A B2 C2 39 00 00 00 8C
Found a DS2413: 3A 8E AE 39 00 00 00 2C
Found a DS2413: 3A E5 B6 39 00 00 00 55

Here is what the code with my changes.

#include <OneWire.h>

#define DS2413_ONEWIRE_PIN  (4)

#define DS2413_FAMILY_ID    0x3A
#define DS2413_ACCESS_READ  0xF5
#define DS2413_ACCESS_WRITE 0x5A
#define DS2413_ACK_SUCCESS  0xAA
#define DS2413_ACK_ERROR    0xFF

OneWire oneWire(DS2413_ONEWIRE_PIN);
uint8_t address[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };

void printBytes(uint8_t* addr, uint8_t count, bool newline=0)
{
  for (uint8_t i = 0; i < count; i++)
  {
    Serial.print(addr[i]>>4, HEX);
    Serial.print(addr[i]&0x0f, HEX);
    Serial.print(" ");
  }
  if (newline)
  {
    Serial.println();
  }
}

byte read(void)
{
  bool ok = false;
  uint8_t results;

  oneWire.reset();
  oneWire.select(address);
  oneWire.write(DS2413_ACCESS_READ);

  results = oneWire.read();                 /* Get the register results   */
  ok = (!results & 0x0F) == (results >> 4); /* Compare nibbles            */
  results &= 0x0F;                          /* Clear inverted values      */

  oneWire.reset();

  // return ok ? results : -1;
  return results;
}

bool write(uint8_t state)
{
  uint8_t ack = 0;

  /* Top six bits must '1' */
  state |= 0xFC;

  oneWire.reset();
  oneWire.select(address);
  oneWire.write(DS2413_ACCESS_WRITE);
  oneWire.write(state);
  oneWire.write(~state);                    /* Invert data and resend     */
  ack = oneWire.read();                     /* 0xAA=success, 0xFF=failure */
  if (ack == DS2413_ACK_SUCCESS)
  {
    oneWire.read();                          /* Read the status byte      */
  }
  oneWire.reset();

  return (ack == DS2413_ACK_SUCCESS ? true : false);
}

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

  Serial.println(F("Looking for a DS2413 on the bus"));

  /* Try to find a device on the bus */
  oneWire.reset_search();
  delay(250);
  while (oneWire.search(address)) {
       printBytes(address, 8);
       Serial.println(F("No device found on the bus!"));
}
  /* Check the CRC in the device address */
  if (OneWire::crc8(address, 7) != address[7])
  {
    Serial.println(F("Invalid CRC!"));
    return;
  }

  /* Make sure we have a DS2413 */
  if (address[0] != DS2413_FAMILY_ID)
  {
    printBytes(address, 8);
    Serial.println(F(" is not a DS2413!"));
    return;
  }

  while (oneWire.search(address)) {
  Serial.print(F("Found a DS2413: "));
  printBytes(address, 8);
  Serial.println(F(""));
}
}

void loop(void)
{
  /* Read */
  /*
  uint8_t state = read();
  if (state == -1)
    Serial.println(F("Failed reading the DS2413"));
  else
    Serial.println(state, BIN);
  */

  /* Write */
  bool ok = false;
  ok = write(0x3);
  if (!ok) Serial.println(F("Wire failed"));
  delay(1000);
  ok = write(0x0);
  if (!ok) Serial.println(F("Wire failed"));
  delay(1000);
}

You have two detection loop in your setup function.
This one can be safely deleted as for each detected device it will print the error message

while (oneWire.search(address)) {
   printBytes(address, 8);
   Serial.println(F("No device found on the bus!"));

}


char array comparison I'm having some issues dealing with strings in a small Arduino app.
I wonder why this code works:

mqtt.setServer("192.168.1.42", port);

and this code doesn't:

IPAddress ip = MDNS.queryHost(...);
mqtt.setServer(ip.toString().c_str(), port);

Even when strcmp returns 0 when I compare both:

strcmp(ip.toString().c_str(), "192.168.1.42"); // output = 0 => equality

I've also tried other alternatives, such as creating a char array, with no luck:

String ipstr = ip.toString();
char ipchar[ipstr.length() + 1];
ipstr.toCharArray(ipchar, ipstr.length() + 1);

mqtt.setServer(ipchar, port);

All alternatives compile, but the mqtt connection is never established later on. I must be missing something obvious because it works when I hardcode the "192.168.1.42" string.

PubSubClient::setServer(const char * domain, uint16_t port) just saves the pointer, it doesn't copy the string (probably because it expects a static string literal).
(Source)
In your case, when ip goes out of scope, the pointer is no longer valid, so it won't work.

Just use the PubSubClient::setServer(IPAddress ip, uint16_t port) function instead.
(Source)

Always read the API documentation, most libraries have one, even though it can be hard to find. The ReadMe and GitHub Wiki pages are a good place to start.
If that's insufficient (not uncommon for open source projects), read the header files, which list all functions of the library.
If you still have doubts about what a function does, refer to the actual implementation files.


arduino boards manager configuration I installed the Arduino IDE 1.6.4, and used the "boards manager" to install the package for Arduino Due.

I am using c++11 in my project so i need to add the compiler.cpp.extra_flags=-std=gnu++11 like i did in the /Applications/Arduino.app/Contents/Java/hardware/arduino/platform.txt file (i am on MacOSX).
It seems that arduino is ignoring that file and using a configuration coming from somewhere else.

Where is the downloaded package installed? Can it be configured?

Ok, as @IgnacioVazquez-Abrams suggested: the configuration files for the plugins can be found in the Arduino ide preferences directory. Click the menu Arduino->Preferences (under macosx) at the bottom of the window there is the clickable path of the preferences.txt file. In the same folder as that file you will find a packages folder, where the plugins are downloaded.


Iteed SD card breakout info for Arduino I got an SD card breakout from an online shop, its the iteed kind without the level shifter, it has the 3.3 / 5 V switch. I cannot find any libraries or write example for it.

Has anyone dealt with it before with Arduino? I have tried finding info but I only get the level shifter kind that has the MOSI pins!

enter image description here

So, a quick google for "Itead SD card breakout" comes up with their website/wiki where there is a schematic.  Can't believe you did not try this.  It is just that - a breakout board.  It will allow you to connect Arduino to an SD card.  You can look up any generic example for SD + Arduino on the web.

They explicitly say

  It can work with 5V or 3.3V power supply, and both 5V/3.3V IO operation level. It can be controlled directly by a wide range of microcontrollers such as Arduino, AVR, PIC, ARM and MSP430.


Arduino IDE automatic tools I know that the Arduino IDE does some simple tasks automatically: for example it creates function prototypes, but this function sometimes fails.

Does that IDE run other hidden "pre-precompiler" tasks?

Is there a way to disable them? (this question refers especially to the function prototypes creator).

The IDE runs a "preprocessing" routine. As well as adding prototypes it also:

Adds #include <Arduino.h> to the start of your sketch
Removes comments (or the older versions did, I am not sure about arduino-builder)
Identifies the libraries #included in the sketch

The latter is used to build the list of -I ... directories to add to the command line. Removing of comments was chiefly to make finding functions easier for making function prototypes (though there are better ways of doing both those and arduino-builder might use them).

Can you disable it? No. Not for .ino files. However, any .cpp files added to your project are treated as vanilla C++ source code and aren't preprocessed in this way.


Cannot obtain reading from meter (Modbus) I have a system in which I am taking readings from a meter and processing it through an Arduino Nano. My code looks as follows:

#include <SoftwareSerial.h>

#define SerialControl 7
#define RS485Tx HIGH
#define RS485Rx LOW

SoftwareSerial RS485Serial(11, 12);
uint8_t window[8]; // Initialising window of 8 bytes

byte SendKWh[] = { 0x01, 0x03, 0x40, 0x34, 0x00, 0x02, 0x90, 0x05 };

// 0x01: Meter Address, 0x03: Read Function Code, 0x40: Register Address Variable (Start address high bit)
// 0x34: Register Address Variable (Start address low bit)
// 0x00: Register Quantity (High Bit), 0x02: Register Quantity (Low Bit)
// 0x90: CRC check code (CRC code Low bit)
// 0x05: CRC check code (CRC code High bit)

void dumpWin() {
  for (int i = 0; i < 8; i++) {
    Serial.print(window[i], HEX);
    Serial.print(" ");
  }
  Serial.println();
}

void ReadRx() {
  // Sliding Window Implementation for reading data
  if(RS485Serial.available()) {
    uint8_t b = RS485Serial.read();
    dumpWin();
    // Slide the contents of the array down
    for (uint8_t i = 0; i < 7; i++) {
      window[i] = window[i+1];
    }
    window[7] = b; // Next frame inserted at the top of previous
    if ((window[0] == 0x01) && (window[1] == 0x03) &&
      (window[2] == 0x40) && (window[3] == 0x34)) {
      // Doing something with window[4] and window[5] here
    }
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(SerialControl, OUTPUT);
  RS485Serial.begin(9600);
}

void loop() {
  static uint32_t ts = millis();
  if (millis() - ts >= 2000) {
    ts = millis();
    digitalWrite(SerialControl, RS485Tx);
    RS485Serial.write(SendKWh, sizeof(SendKWh));
    RS485Serial.flush();
    digitalWrite(SerialControl, RS485Rx);
    RS485Serial.listen();
  }
  ReadRx();
}

The ReadRx() is behaving odd and dumpWin() is giving 0 0 0 0 0 0 0 0 output. I have been trying but I'm not able to figure out where am I going wrong. Your help is appreciated!

EDIT 2: I changed the code as suggested by @Majenko but still window[] O/P is 0 for all. I am not able to understand as to why it is not able to read the values from RS485Serial.

You need to stop thinking quite so linearly. You are working with asynchronous systems, so your code has to be asynchronous too.

Something more like this:

#include <SoftwareSerial.h>

#define SerialControl 7

#define RS485Tx HIGH
#define RS485Rx LOW

SoftwareSerial RS485Serial(11, 12);

byte SendKWh[] = { 0x01, 0x03, 0x40, 0x34, 0x00, 0x02, 0x90, 0x05 };

// 0x01: Meter Address, 0x03: Read Function Code, 0x40: Register Address Variable (Start address high bit)
// 0x34: Register Address Variable (Start address low bit)
// 0x00: Register Quantity (High Bit), 0x02: Register Quantity (Low Bit)
// 0x90: CRC check code (CRC code Low bit)
// 0x05: CRC check code (CRC code High bit)

uint8_t window[8]; // Initialising window of 8 bytes

void dumpWin() {
  for (int i = 0; i < 8; i++) {
    Serial.print(window[i], HEX);
    Serial.print(" ");
  }
  Serial.println();
}

void ReadRx() {
  if(RS485Serial.available()) {
    uint8_t b = RS485Serial.read();
    dumpWin();
    // Slide the contents of the array down
    for (uint8_t i = 0; i < 7; i++) {
      window[i] = window[i+1];
    }

    window[7] = b; // Next frame inserted at the top of previous

    if ((window[0] == 0x01) && (window[1] == 0x03) &&
        (window[2] == 0x40) && (window[3] == 0x34)) {
          // Doing something with window[4] and window[5] here
    }
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(SerialControl, OUTPUT);
  digitalWrite(SerialControl, RS485Rx);
  RS485Serial.begin(9600);

}

void loop() {
  static uint32_t ts = millis();

  if (millis() - ts >= 2000) {
      ts = millis();
      digitalWrite(SerialControl, RS485Tx);
      RS485Serial.write(SendKWh, sizeof(SendKWh));
      RS485Serial.flush();
      digitalWrite(SerialControl, RS485Rx);
      RS485Serial.listen();
  }

  ReadRx();
}

Notice how I use millis() to send the command every 2 seconds asynchronously (i.e., without delay()). The RS485 is kept in READ mode except for the brief moment while you send. Also note the use of flush()  to wait until the last symbol has been transmitted by the UART (software in this case) interface. It's important, otherwise you may cut off the transmission part way through (I don't think it's such a problem with SoftwareSerial, but with a hardware UART missing it out would be fatal).

The reading just reads one character and returns to the loop. Each iteration through the loop will (if a character is available) read just one character. Only when all 8 have been received and the contents of the window match up can you process anything (which you would put in place of the comment).

This method also leaves you free to implement other things in loop(), as long as they don't use delay() as well.


Using I2C: Master Reader and Writer I'm using I2C and the Arduino Library (Wire) to communicate between two Arduinos, and my code isn't working. It's supposed to read in an int from the slave, write a value to the slave, then read back that value. I'm expecting "0 4", but i keep getting "0 0". Does this mean that the slave isn't registering the write?

Master code:

#include <Wire.h>

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

void ffsis()
{
  //request i
  Wire.requestFrom(2, 1);
  int i = Wire.read();
  Serial.print(i);

  //send n seed
  Wire.beginTransmission(2);
  Wire.write(12);
  Wire.endTransmission();

  Serial.print(" ");

  //request n
  Wire.requestFrom(2, 1);
  int n = Wire.read();
  Serial.print(n);
}

void loop()
{
  delay(100);
}

Slave code:

#include <Wire.h>

void setup()
{
  Wire.begin(2);
  Wire.onRequest(requestEvents);
  Wire.onReceive(receiveEvents);
}

void loop(){}

int n = 0;

void requestEvents()
{
  Wire.write(n);
}

void receiveEvents(int howMany)
{
  int n = wire.read();
}

int n = wire.read();

"Wire" should be capitalized.

Amplifying on Ken's reply, you have two variables called "n", and the global one should be declared volatile. Also, I2C deals in bytes, not ints, so preferably do this:

#include <Wire.h>

void setup()
{
  Wire.begin(2);
  Wire.onRequest(requestEvents);
  Wire.onReceive(receiveEvents);
}

void loop(){}

volatile byte n = 0;

void requestEvents()
{
  Wire.write(n);
}

void receiveEvents(int howMany)
{
  n = Wire.read();
}

In addition, the address 2 is a reserved address.

  Address 0 is reserved as a "broadcast" address, addresses 1 to 7 are reserved for other purposes, and addresses 120 to 127 are reserved for future use.

You should choose an address in the range 8 to 119.

Reference

I2C - Two-Wire Peripheral Interface - for Arduino
Official I2C specification


USART, SPI or Bit-Bang for the continuous transfer of bytes without inserted extra bits I have heard that

The SPI hardware introduces a 9th, HIGH bit between bytes
USART still uses start and stop bits when in synchronous mode

Are both these statements true? Can I modify the built-in SPI library to avoid #1? Or will I have to bit-bang the protocol needed?

Are both these statements true?

Neither of those statements are true.

SPI never inserts extra bits. That would break everything if it did. What you are probably seeing (or think you are seeing) is a delay between bytes being sent. That delay is irrelevant, since the data is only ever sampled on an edge of the clock signal (which edge depends on the mode of the SPI communication) and with no clock edge in that delay period there is no data.

USART in synchronous mode is SPI. There are no start or stop bits in synchronous mode, since the clock is used to synchronise the communication rather than needing start or stop bits.


Creating an array of structures which store bitmaps to work with u8glib I've tried reading the documentations and I'm getting desperate because I can't find anything.

I need to create an array of structures, which contains a bitmap stored in PROGMEM space (because of issues with memory usage).

The bitmaps are created as follows:

const uint8_t pat[] PROGMEM = {
...
};

Then I need to create a structure like this:

typedef struct{
    uint8_t bitmap[8];
} chars;

chars allChars[1];

but the compiler doesn't like that for some reason and spit out a bunch on invalid conversion from const to char so it was clear I couldn't use that!
My next attempt was to create a pointer to the pattern like so:

typedef struct{
    const uint8_t *bitmap[8];
} chars;

chars allChars[1];

This time it again gave warnings about invalid conversion but at least compiled!
I then tried to write the entire code and run it:

#include "U8glib.h"
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0);

typedef struct{
    const uint8_t *bitmap[8];
} chars;

chars allChars[1];

const uint8_t pat[] PROGMEM = {
  0xff,
  0x00,
  0xff,
  0x00,
  0xff,
  0x00,
  0xff,
  0x66
};

void draw(void) {
  u8g.drawBitmapP( 37, 28, 1, 8, pat);
  u8g.drawBitmapP( 74, 28, 1, 8, (char*) allChars[0].bitmap);
}

void setup(void) {
  allChars[0]= (chars) {*pat};
}

void loop(void) {
  draw();
  while(true);
}

the first line where I have used the pattern directly in the draw function, works perfectly fine, but the second line which retrieves the value from the pointer draws some weird noise shape (I'm guessing memory dump of an address or something)!

Is it even possible to create a struct with one of the variables being just a pointer to the constants that I have defined earlier? I'm pretty sure I'm doing something very wrong as I'm not familiar with using pointers and addresses and whatnot, so it would be great if someone could help with these issues!

That still wouldn't solve the issue with struct!
I think I have found a glitch in GCC compiler where if you define your struct in dynamic memory rather than PROGMEM, even if you use a buffer and fetch the data using memcpy_P, it will return the correct value while printing, but when you copy it again to allChars[0].bitmap , the wrong value is copied! the thing that solved the issue was adding PROGMEM to the struct like below:

typedef struct {
  unsigned int ascii;
  int size[2];
  const PROGMEM unsigned char *bitmap;
} chars;

I have not yet encountered any compilers that are this specific and don't even allow transfer between memory spaces correctly. (Not to mention other issues with GCC linker that are brought up by david from eevblog like stack overflow without warning, etc). They really need to solve issues like this as this compiler is one of the most frequently used on different platforms.

anyways, here is the final code if anyone finds it useful (I will probably end up making a youtube video about it later):

#include "U8glib.h"
//U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE);
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0);

typedef struct {
  unsigned int ascii;
  int size[2];
  const PROGMEM unsigned char *bitmap;
} chars;

chars allChars[1];

const unsigned char pat[] PROGMEM = {
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x01, 0xfc, 0x00,  //.......%%%%%%%.......
  0x0f, 0xff, 0x00,  //....%%%%%%%%%%%%.....
  0x1f, 0xff, 0xc0,  //...%%%%%%%%%%%%%%%...
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x7f, 0xff, 0xf0,  //.%%%%%%%%%%%%%%%%%%%.
  0x7f, 0xdf, 0xf0,  //.%%%%%%%%%.%%%%%%%%%.
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0x7f, 0xdf, 0xf0,  //.%%%%%%%%%.%%%%%%%%%.
  0x7f, 0xff, 0xf0,  //.%%%%%%%%%%%%%%%%%%%.
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x1f, 0xff, 0xc0,  //...%%%%%%%%%%%%%%%...
  0x0f, 0xff, 0x80,  //....%%%%%%%%%%%%%....
  0x01, 0xfc, 0x00,  //.......%%%%%%%.......
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
};

void charToBitmap(int x, int y, char chr){
  for(unsigned int i=0; i<sizeof(allChars);i++){
    if (allChars[i].ascii=chr){
      u8g.drawBitmapP( x, y, allChars[i].size[0], allChars[i].size[1], allChars[i].bitmap);
      break;
    }
  }
}

void draw(void) {
  charToBitmap(0,0,'0');
}

void setup(void) {
  allChars[0] = (chars) {48,{3,54},pat};
}

void loop(void) {
    u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );
}


Why is my Serial port not printing the right output? am working with and Arduino nano and according to this, I can append strings to numbers by doing: stringThree =  stringOne + 123; but
when I do:

sensorValue = analogRead(A0);
String x1 = "{\"Volt\":"+sensorValue;
Serial.print(x1);

I get this unwanted output!

  =gëÙrïË:_³ß»þ™¹Æ3+Ç#ÿ¼¿.Õ[Oû/g¯>ïÿ1þ†lú0

but doing this it works fine.

sensorValue = analogRead(A0);
String x1 = "{\"Volt\":";
x1 += sensorValue;
Serial.print(x1);

  "Volt":646

why?

In the first example you are adding an integer to the address of a string literal and then converting it to a String.

In the second example you are converting a string literal to a String and then appending an integer.

The key point here is string literal. The compiler just sees it as an address in flash memory. It's down to the functions you use with that address that define it as a string. So when you add an integer to it you are just adding an integer to the address, which of course changes the address. So then when you go to convert whatever is at that address to a String you end up with garbage.


Resistor on SPI Chip Select Pin I'm working on a modular CANBUS system for offroad racing. The idea right now is that the main Arduino (1284p at the moment) will be the only one connected to CANBUS, and other modules will have their own atmega's that will communicate with the master over I2C. They will not be physically on the same PCB, but will be physically within inches of each other. One module will have 8 MAX31865 IC's for interfacing with RTD's. The 31865 is not compatible with 5V microcontrollers, which right now we planned on running the Atmega's at 5V. Since the IC's are SPI, they can all share a MOSI, MISO, and CLK bus, so only two channels of a hex converter. For the Chip Select pin, would it be acceptable to use a resistor to decrease the voltage instead of using an additional 8 channels of hex converting?

What would the upsides/downsides be of using an atmega running at 3.3v for the module with the MAX31865's and just using a hex converter on SDA/SCL for the I2C communication to the master? What atmega I use for this is flexible.

would it be acceptable to use a resistor to decrease the voltage

I don't see any big problem with using a voltage divider for chip select.

  What would the upsides/downsides be of using an atmega running at 3.3v for the module with the MAX31865's

At 3.3V you can only run at 13 MHz or less (so in practice, 8 MHz, unless you want to do a lot of fiddling around). This may or may not matter to you. At a lower voltage it uses less power which can be a plus, and you don't need to worry about level converters.

  and just using a hex converter on SDA/SCL for the I2C communication to the master?

Do you mean a level converter?


http request in time intervals I'm doing a program that receives data from a web page every so often, but only receives the data once and then receives everything blank. I need help to receive the data every time indefinitely. I am using arduino uno with arduino etherner shield

My code:

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress ip(192, 168, 0, 177);
EthernetClient client;

int REDLed= 2;
int GREENLed= 3;
int BLUELed= 4;

void setup()
{
  pinMode(REDLed, OUTPUT);
  pinMode(GREENLed, OUTPUT);
  pinMode(GREENLed, OUTPUT);
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
  Serial.println("power up" );
  delay(3000);
}

void loop()
{
  Serial.println("SubmitHttpRequest - started" );
  SubmitHttpRequest();
  Serial.println("SubmitHttpRequest - finished" );
  delay(10000);
}

void SubmitHttpRequest()
{
  if (client.connect(server, 80))
  {
    Serial.println("connected");
    client.println("GET /arduino/getstate.php?color=All HTTP/1.1");
    client.println("Host: cybertodo.mx");
    client.println("Connection: close");
    client.println();
  }
  else
  {
    Serial.println("connection failed");
  }
  delay(100);
  changeLed();
}

void changeLed()
{
  String content = "";
  Serial.println(client.available());
  while(client.available()!=0)
  {
    content = content + String(char (client.read()));
  }
  Serial.println(content);
  if(content.substring(30,31)== "1")
  {
    digitalWrite(REDLed, HIGH);
  }
  else if (content.substring(30,31)== "0")
  {
    digitalWrite(REDLed, LOW);
  }

  if(content.substring(31,32)== "1")
  {
    digitalWrite(GREENLed, HIGH);
  }
  else if (content.substring(31,32)== "0")
  {
    digitalWrite(GREENLed, LOW);
  }

  if(content.substring(32,33)== "1")
  {
    digitalWrite(BLUELed, HIGH);
  }
  else if (content.substring(32,33)== "0")
  {
    digitalWrite(BLUELed, LOW);
  }
  content = "";
}

Immediately after making the request when reading client.available() will be 0 since no data was received yet so:

  while(client.available()!=0)
  {
    content = content + String(char (client.read()));
  }

Will never actually run. Try something like:

unsigned long last = millis();
String content = "";

while(client.connected()) {
  int len = client.available();
  if(len > 0) {
    last = millis();

    char buff[len];
    for(int i = 0; i < len; i++) {
      buff[i] = client.read();
    }
    content += String(buff);

  } else {
    if(millis() - last > 2000) {
      client.stop();
      return;
    }
    delay(1);
  }
}

Also note if you use Connection: close on the client then you must close the connection. This example doesn't do that until 2 seconds have passed. To do this properly you'd need to also add header parsing to your client and close the connection once the amount specified in Content-Length is received.


Drawing a line at a given angle Im attempting a device that measures lean angle. I have an ESP8266 + MPU6050 + SSD1306 setup, and I've managed to build a shaky but somewhat functioning device.
What Id like to do is use the Adafruit_SSD1306 library to call the display.drawLine(x, y, x1, y1, color) function and have the line drawn to the measured angle output of the MPU6050.
The screen I'm using is 128 X 64
The MPU6050 is initially laying flat at 180 degrees, but is set and displayed as 0 degrees of tilt. The line is drawn vertically on the screen and pivots around x1 and y1 at 64, 64 respectively in the middle at the bottom of the screen.
If the MPU6050 pivots left like in the picture, the angle measurement itself is roughly correct, but the line indicator is showing more like 30 degrees than 45, and gets worse the larger the angle value.

My code:
#include <Adafruit_MPU6050.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_Sensor.h>

const int MPU_addr=0x68;
int16_t axis_X,axis_Y,axis_Z;

Adafruit_MPU6050 mpu;
Adafruit_SSD1306 display = Adafruit_SSD1306(128, 64, &Wire);

int minVal=265;
int maxVal=402;

double x;
double y;
double z;
int tiltAngle;
double y2;

void setup(){
  Serial.begin(9600);
  Serial.println("MPU6050 OLED demo");

  if (!mpu.begin()) {
    Serial.println("Sensor init failed");
    while (1)
      yield();
  }
  Serial.println("Found a MPU-6050 sensor");

    // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x64
    Serial.println(F("SSD1306 allocation failed"));
    for (;;)
      ; // Don't proceed, loop forever
  }

  display.display();
  delay(500); // Pause for 2 seconds
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setRotation(0);
}
void loop(){
  display.clearDisplay();
  display.setCursor(0, 0);

  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);
  axis_X=Wire.read()<<8|Wire.read();
  axis_Y=Wire.read()<<8|Wire.read();
  axis_Z=Wire.read()<<8|Wire.read();
    int xAng = map(axis_X,minVal,maxVal,-90,90);
    int yAng = map(axis_Y,minVal,maxVal,-90,90);
    int zAng = map(axis_Z,minVal,maxVal,-90,90);

     x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
     y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI);
     z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);

     tiltAngle = (int) x - 180; // we want the tilt angle to be 0 degrees
     display.println(" ");
     display.println(" ");
     display.println(" ");

     // display only positive angle values for either direction of tilt
     if(tiltAngle > 0){ display.print(tiltAngle);}
     else if (tiltAngle < 0) { display.print(tiltAngle * -1);}
     else {display.print(tiltAngle);}

     display.drawLine(-tiltAngle + 64, 0,64,64,WHITE);
     display.display();
     delay(100);
}

Im aware that for my first y co-ordinate I will need to use some kind of formula to get the line to move down from 0 (the top of the screen) as the lean angle gets greater. I'm hoping someone could point me in the right direction for drawing the line at the angle given by the MPU6050.
I did consider using case statements for each angle value and drawing the line with fixed co-ordinates based on each angle value. But that seems too compute intensive and could take up too much of the DRAM. Is anyone aware of a simple formula I could use? Thanks for reading.

Use trigonometry (sin() and cos()) functions to get the right x and y coordinates.
I would consider replacing your drawLine() command with something like this (untested) assuming the tiltAngle is in degrees from -90 to +90 (with 0 degrees is straight up) and you want to draw a line at this angle from the origin (63, 63) with a radius of 64.
float tiltAngleRad = tiltAngle * DEG_TO_RAD; // convert angle to radians
int xEnd = 63 + 64 * sin (tiltAngleRad); // Ending x-coordinate offset & radius
int yEnd = 63 - 64 * cos (tiltAngleRad); // Ending y-coordinate offset & radius
display.drawLine (63, 63, xEnd, yEnd);

You might have to experiment with the offset and radius but I believe this will get you close yo what you want.


Are these components connected correctly? I intend to use two ultrasonic sensors as input and a vibration motor as its output, is this connected correctly?

As part of my project, I intend to use an ultrasonic sensor to feed in distance data and react through vibration motor. I have to confirm this arrangement will work but I don't own an Arduino.

in short: Definitely Not.

1 : you do really need to connect the trigger pins of the ultrassonic sensors, or else you will not be able to "trigger" them.
Read the ultrassound library examples, they may help you.

2 : I am pretty sure an analog (or digital for that matter) pin in arduino nano cannot sink the current needed to make the motor spin. You are going to fry that pin/port or even brick the entire arduino.
Read on power mosfets for the solution of that.

Moreover, i don't think the 5v out of the arduino feeding the motor is a good idea as well, as the current given by its internal regulator may not be enough for the motor as well.


Programming the ATMega328P without Arduino board always returns the error: avrdude: stk500_recv(): programmer is not responding I have a microcontroller: ATMega328P.
I don't have any Arduino Uno board.

I want to program the ATMega328P using my FTDI programmer.

But when I try to program the ATMega328P without Arduino board I always get this error:

avrdude: stk500_recv(): programmer is not responding

I've followed this YouTube Tutorial to build this.

And ended up with this diagram:

All the connections seems OK.

I choose the board: "Arduino Pro or Pro Mini" because only with this one I can choose the correct processor: "ATMega328P (5V, 16MHz)"

The port is correct: "/dev/ttyUSB0"

And as for the the programmer I've choose: "USBasp", which I don't know if this is correct. I've used this FTDI programmer to program the STM32 microcontroller and the programmer was "Serial", which I don't see the very same option here.

I'm lost, what am I missing up here?

BTW I've seen this, this and this but couldn't get it fixed.

A new chip cannot be programmed in that manner until it has the Bootloader installed. The Bootloader starts after a reset and monitors the serial interface to see if something is attempting to download code via the serial port.

Selecting a Programmer has no effect on serial download, that only comes into play when Programming via the SPI pins SCK/MOSI/MISO/Reset/Power/Gnd.

Your "design" needs a couple more parts: 0.1uF caps between VCC and Gnd, and AVCC and Gnd.

The Cryslal and 22pF caps could also be a lot closer to the device - like right next to it.

I can't read the FTDI markings, so I can't tell if you have Rx and Tx swapped there.


Arduino ISP ATtiny problems As I was trying to program my ATtiny chip with my arduino, I ran across some problems. Note that I know that this problem is faced almost in every Q and A site and forum so don't flag me as repeat yet. (I was trying to burn the bootloader so my chip runs at 8MHz)

So this is the error code:

C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -v -v -v -pattiny85 -cstk500v1 -PCOM1 -b19200 -e -Uefuse:w:0xff:m -Uhfuse:w:0xdf:m -Ulfuse:w:0xe2:m

 avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

 System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM1
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x03

avrdude done.  Thank you.

Error while burning bootloader.

* deleted attempt 2 to 9 *

Although a solution to this problem will be very nice, that is not my intention here. I tried almost all solutions I have found and non of them work, and I want to know why. So these are my questions:

What does this code actually mean? The for example the "programmer", is it referring to the Arduino or the ATtiny(or the highly unlikely, laptop that im using.)
How do I access more error codes, if there are any, as I think that these codes really do not tell that much.
[Solved]To prevent Arduino from auto-resetting, almost all tutorials connect the Reset pin to the Ground pin with a 10uF capacitor, and I don't have one. I tried with various other capacitors that I have(22uF, 0.4uF, 0.22uF, 47uF, and 330uF). I do not know how does the capacitance affect the anti auto-resetting function, so some explanation here is helpful.
[solved]

EDIT: I disconnected the ATtiny and the same error code persists. This, I conclude as either I never had a proper connection with the ATtiny, or the problem is with the communication of my laptop with the Arduino.

I did not download Arduino as ISP into my arduino. I realize how much of an idiot I am. The capacitor wasn't even needed for some reasons. I might make an intensive tutorial on this project.


Hold all "millis()" values in an array? I'm working on a project where I could have up to six devices connected to an arduino, it might be the case that not all of them will be attached at the same time, and all of them need to be able to receive PWM signals but without using delay().

There are a number of different PWM patterns already programmed into the code, what I'd like to do is be able to assign more than one device to a single pattern, and start/stop the patterns at different times to different devices.

I have a python script (and soon an Android app) that sends a message in the following format to the device:

<int(pin_number), string(pattern_name), int(highest_pwm_value 0 - 255), int(delay_between_pulses_in_seconds)>

Is there some way of coding something like the following, and if so, how would I go about it?

array timings[];

void fade(unsigned long thisMillis, int fadeInterval, int maxPWM, int motor_pin) {
  if (thisMillis - timings[motor_pin] >= fadeInterval) {
    // yup, it's time!
    if (fadeDirection == 1) {
      fadeValue = fadeValue + fadeIncrement;
      if (fadeValue >= maxPWM) {
        // At max, limit and change direction
        fadeValue = maxPWM;
        fadeDirection = 0;
      }
    } else {
      //if we aren't going up, we're going down
      fadeValue = fadeValue - fadeIncrement;
      if (fadeValue <= minPWM) {
        // At min, limit and change direction
        fadeValue = minPWM;
        fadeDirection = 1;
      }
    }
    // Only need to update when it changes
    analogWrite(motor_pin, fadeValue);

    // reset millis for the next iteration (fade timer only)
    timings[motor_pin] = thisMillis;
  }
}

The bit that I'm unsure about is how the array should be defined etc, as I'm primarily a python developer so it's rare I have to explicitly set the type of an item in an array!

This is a classic example where you want to create a class.  A class will contain all the control logic for dealing with one pin - all the functions, all the variables, etc.

Then you just create as many instances of the class as you need for your different pins. Each one is completely separate from the other, and each one can be controlled at will.

For instance, you might make something like this (untested):

class FaderPin {

    private:
        uint32_t timestamp;
        int motor_pin;
        int fadeInterval;
        int minPWM;
        int maxPWM;
        int fadeDirection;
        int fadeValue;

    public:
        FaderPin(int pin, int minp, int maxp, int interval) {
            motor_pin = pin;
            minPWM = minp;
            maxPWM = maxp;
            fadeInterval = interval;
            fadeDirection = 1;
            fadeValue = minp;
            timestamp = millis();
        }

        void fade() {
            uint32_t thisMillis = millis();
            if (thisMillis - timestamp >= fadeInterval) {
                // yup, it's time!
                if (fadeDirection == 1) {
                    fadeValue = fadeValue + fadeIncrement;
                    if (fadeValue >= maxPWM) {
                        // At max, limit and change direction
                        fadeValue = maxPWM;
                        fadeDirection = 0;
                    }
                } else {
                    //if we aren't going up, we're going down
                    fadeValue = fadeValue - fadeIncrement;
                    if (fadeValue <= minPWM) {
                        // At min, limit and change direction
                        fadeValue = minPWM;
                        fadeDirection = 1;
                    }
               }
               // Only need to update when it changes
               analogWrite(motor_pin, fadeValue);
               // reset millis for the next iteration (fade timer only)
               timestamp = thisMillis;
           }
       }

};

Then you can:

FadePin motorOne(5, 0, 255, 10);
FadePin motorTwo(6, 0, 255, 10);

And regularly call:

motorOne.fade();
motorTwo.fade();


Help Connecting Arduino Uno To Computer I am A Newbie to Arduino

I have a Windows 7 PC. Last Time I bought an Arduino Uno Clone but after working for a day, it stopped detecting on the port. So I bought a new Clone Of different brand. Now I Want in which sequence should I install its drivers, Coonect it, Unzip Arduino IDE...Reboot??

I dont want a problem this time. Another question is Should I first connect the clone and then Install its drivers Or first install drivers and then plug the board? When Is the reboot required?

Product Link : https://m.ebay.in/itm?itemId=121708881208

Please Explain...
Thanks In Advance

I have shorted my bords a few time and they always came back to "life" after a minute. Maybe you should be more concern about the voltage you supply to the board. Even if it can take up to 12 volt I never use more then 9 volt on the board. And if you run motors on them its always good to supply them with an external power source and use something like a H bridge to power your devices. I made mistakes and my board are still in mint conditions.


Playing Audio from SD - Get VU, or audio waveform I am using the library SimpleSDAudio to play a song from my SD card to an op-amp later in the circuit. I would like to take a sample from the audio pin (possibly with a Analog read) to power some visualizations (VU, etc.), although I am getting some unexpected readings off the audio pin.

I tried to bias the audio using this post, but got the same results.

I'm not sure if I am headed in the wrong direction here, any help would be amazing.

#include <SimpleSDAudio.h>
int ReadPin = A0;
int AudioValue = 0;

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

  Serial.print(F("\nInitializing SD card..."));

  if (!SdPlay.init(SSDA_MODE_FULLRATE | SSDA_MODE_MONO | SSDA_MODE_AUTOWORKER)) {
    Serial.println(SdPlay.getLastError());
    while(1);
    } else {
    Serial.println(F("Wiring is correct and a card is present."));
  }

  Serial.print(F("Looking for THRILLER.WAV... "));
  if(!SdPlay.setFile("THRILLER.WAV")) {
      Serial.println(F(" not found on card! Error code: "));
      Serial.println(SdPlay.getLastError());
      while(1);
  } else {
     Serial.println(F("found."));
  }

  Serial.print(F("Playing... "));
  SdPlay.play();

}

  void loop() {
    AudioValue = analogRead(ReadPin);
    Serial.println(AudioValue);
    delay(50);

}

My expected output of sampling the output from A0:

You are sampling your audio signal with only 20Hz. That is very low frequency for an audio signal, that humans can hear. Generally you need to sample your signal with double of the highest containing frequency at minimum, or you will only get nonsense (you can google Nyquist Rate for more information). Also a Nano does not have a real DAC, so the audio is generated via a PWM signal, which turn the line on and off very fast, so you only see the waveform only, if you apply a low pass filter (like a speaker will do, because it cannot move that fast).

But directly sampling the audio signal is overly complex, only for making a VU meter visualization. These visualizations are way slower, than the actual audio signal. So you need to take the mean value over a specific time interval. Best you can reach this by building a low pass filter using a resistor and a capacitor. You can sample the output of that filter, which will only have lower frequencies. The sampling frequency then should be double of the cut of frequency of the filter at minimum.

Of course it is also possible to do all this in software, but for this you would have to change the library and I guess you don't want to do this.


digitalWrite queued signals? I have this simple code who send a signal to a android phone when I press a button:

const int botonPinD = 8;
const int relayPin =  12;
int retardo = 100;
int finBoton=1000;

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

  pinMode(botonPinA, INPUT);
  pinMode(botonPinB, INPUT);
  pinMode(botonPinC, INPUT);
  pinMode(botonPinD, INPUT);
}
void loop(){
    botonD = digitalRead(botonPinD);
    if (botonD == HIGH){
   // for simplicity remove botonA, botonB and botonC code, but it's the same with a few digitalWrite
        digitalWrite(relayPin, HIGH);
        delay(retardo);
        digitalWrite(relayPin, LOW);
        delay(retardo);
        digitalWrite(relayPin, HIGH);
        delay(retardo);
        digitalWrite(relayPin, LOW);
        delay(retardo);
        digitalWrite(relayPin, HIGH);
        delay(retardo);
        digitalWrite(relayPin, LOW);
        delay(retardo);
        digitalWrite(relayPin, HIGH);
        delay(retardo);
        digitalWrite(relayPin, LOW);
        delay(retardo);
        delay(finBoton);
      }
      else{
        digitalWrite(relayPin, LOW);
      }
}

But if I press the button fast (maybe a half a second between clicks) I only receive once the signal.

I'm not very sure about what's happened here (I'm an Arduino newbie). The first signal, has it locked the channel? Can signals be queued? Can I control the way that they are queued?

The main problem I guess you are suffering from is the good old delay() blockage.

delay() is a terrible function and should be avoided at all costs.  Nothing at all can happen while you are running delay() - that means you can't be reading the state of your button - until all your delay() calls have finished.

If you want to queue the pressed of the button you will need to do three things:

You will need to recognise when the button changes from LOW to HIGH, not just "when it is HIGH" as you do now.
You will have to queue that button press somewhere. The simplest way is to maintain a count of how many times the button has been pressed.
You will have to process any pending button presses ("while the count > 0") by triggering your output with the right timing without using delay(), which means using millis() and maintaining state information.


Why doesn't the Ethernet W5100 shield work on Gigabit switch? I have an Arduino Uno with an Ethernet Shield based on the Wiznet W5100 chipset :

It worked like a charm until I had to move it to another location and plugged it to a Gigabit switch. I had no link, the plug LEDs were off, or just on for a fraction of a second then off again.

I tried several switches, router and Internet boxes (french Freebox), and I ended up with the conclusion that it doesn't work when plugged onto a Gigabit switch. On every 10/100 switches, it works.

BUT

I also have a W5100 small module not designed like the shield :

This one is working on Gigabit switches !!!

I did see another post here : WizNet W5100 not connecting to modern switches and routers, where someone told the lower bits of the first MAC Address byte should be 00. So I changed the MAC address to 08:af:01:00:00:03 with no more luck, the shield still doesn't get connectivity.

I googled for this but didn't find any resources. I'm surprised this hasn't come over, knowing that so much ethernet shields are out on the market!

I tried a second shield (like the first picture), same issue : no connectivity on Gigabit switches.

I know other old NICs or laptops that don't support Gigabit are working correctly with Gigabit switches that should "pull down" the port to 100 instead of 1000.

Does anyone have an answer about why it doesn't work and how we can have an Arduino work when connected to a Gigabit switch? (other shields?)

The fix for this is to solder a 120 Ohm resistor between pins 1-2 and 3-6 of the RJ45 socket (where pin 1 is closest to the left side of the socket when looking at the top of the board. (Credit to keithsw1111 for the fix)

See https://forum.arduino.cc/index.php?topic=372779.0 for full details.

I know this was asked a long time ago however this post comes up quite high on a google search of the issue so its good to have reference to the fix.