What am I missing? Send data from Matlab to Arduino to Micro SD First off. This is not in any way a class assignment. This is my own personal work and research. I just want to get that out of the way.

I am learning how to use Matlab with various Arduino projects. I am a seasoned Matlab user but I am fairly new to the entire Arduino space.

I am trying to send some numerical data from Matlab (via a GUI) to my Arduino Uno and have the Arduino write it to my micro SC card. This is a temporary step to my larger project. However, there is no need to go into those specifics as they are outside of the scope of my issues.

I am fairly confident that the Matlab code works and the Arduino code is slightly modified from another project I did where I wrote and read random numbers from my micro SD card.

However, as I run the Matlab code, the Arduino blinks as if it is receiving the data but after I check the micro SD card it remains blank.

I am confident that my Arduino is wired correctly to my micro SD card adapter since this remains the same from my prior project.

Therefore, I am sure I am missing something trivial to get it to work.

I have researched several websites on the subject and their method and mine seem to align very well.

I am fairly certain the problem is in the conditional statement:

if (Serial.available() > 0) {

As you will see.

The Matlab code is below:

arduinoCom = serial('COM3', 'BaudRate', 115200);
sendData = 5;
fopen(arduinoCom);
fprintf(arduinoCom,'%i',sendData); %this will send 5 to the arduino
fclose(arduinoCom);
delete(arduinoCom);

The Arduino code is as follows:

#include <SD.h> // load SD library

int chipSelect = 4;  // Chip select pin for the MicroSD Card Adapter
int incomingByte = 0; // for incoming serial data.
File SDF; // Serial data received is saved here.

void setup() {
     Serial.begin(115200); // start serial connection to print out debug messages and data
     pinMode(chipSelect, OUTPUT); // chip select pin must be set to OUTPUT mode
     if (!SD.begin(chipSelect)) { // Initialize SD card
        Serial.println("Could not initialize SD card."); // if return value is false, something went wrong.
     }
     while (!Serial) {
     }
}

void loop() {
        // Open file, Write data, Close file only when you receive data
        if (Serial.available() > 0) {
           incomingByte = Serial.read();
           SDF = SD.open("SerialDataFile.txt", FILE_WRITE); // open "SerialDataFile.txt" to write data
           SDF.println(incomingByte, DEC); // write ASCII-encoded decimal number to file
           SDF.close(); // close file
           }
}

The expected result would be a file "SerialDataFile.txt" stored on my micro SD card with the value 5.

Thank you for your help!

The board resets on new USB connection with fopen. Wait 2 secs between fopen and fprintf in Mathlab code.


How to check whether my Arduino is working? And how to fix this? I tried my first project with Arduino Uno. But I can't upload any code. Power green LED is working and orange LED is always on, not blinking, and IC also getting hot. What can I do to fix this problem?

My suggestion is to find someone else with an arduino, and get them to test (with their computer, known to be working) uploading to your Arduino. That way, you can tell if the problem is with your computer or the Arduino.

You haven't mentioned what your first project was. The most common mistake #1 is to light up an LED without a resistor. If you do that for a split second, you might (OR MIGHT NOT!) get away with it. If you leave it running for a few seconds, you are almost certainly going to burn out your AtMega (the IC on the board). This might very well result in the symptoms you describe. If this has happened, and your chip (IC) is removable (some are, some aren't), you should be able to buy a new chip of the same kind. An Arduino Uno has an AtMega 328, you will want a DIP package (they are the removable ones), and you will want one with an Arduino Bootloader pre-programmed. Replacing the chip may OR MAY NOT fix the problem. Make sure you note down the orientation of the broken chip before you pull it out - it will fit in, but won't work (and could burn out!) if you put it in the wrong way. There should be a little dimple at one end of the chip, right on the end. It should look like this (possibly without the pin labeling sticker): http://www.jaycar.co.nz/productView.asp?ID=ZZ8726&w=atmega328&form=KEYWORD

If your chip is not removable, or replacing the chip doesn't help, then you will need to get a new Arduino.


Can the Arduino interface with USB devices without the USB host shield? I'm looking to connect various USB-devices to an Arduino Uno (specifically, a gamepad and a webcam, but I'm interested in the general case). Is this possible without using the USB host shield, since the Uno has a USB port and USB-to-serial converter? I could use the shield, but I'm curious if/why it's neccessary.

The Sparkfun website states that:

  The SparkFun USB Host Shield contains all of the digital logic and analog circuitry necessary to implement a full-speed USB peripheral/host controller with your Arduino.

Does the Arduino not already contain this, just needing the proper software (although obviously it's easier to use the already written library for the Host Shield). Or are there hardware limitations?

According to
Can a Ethernet USB Dongle be instead of ethernet shield for arduino?
(Majenko's answer), it can, in theory, be done with the Due, but not with the Uno. In that case, is this because the Uno uses the ATmega16U2 instead of the FTDI FT232RL for USB communication?

First things first you need to learn the basics of how USB works.

In USB there are two main "things": Hosts and Devices.

You have one Host (usually your computer) and many Devices (such as Arduinos, Printers, Scanners, Webcams, WiFi dongles, etc).

Being a host involves knowing about what devices you are going to have attached to you and how to communicate with them. Being a device means just communicating with the host in your own way.

As you can see it is a far more complex job being a host than being a device.

Arduinos are devices. The small USB interface chips they use are very low powered and can only be a device, never a host.

If you want to plug a device into something it has to be a host (note: I am purposely ignoring hubs here).

The Arduino Due uses a far more powerful chip, and that is capable of being a host (using what is known as On-The-Go mode).

To do it with anything less powerful than a Due you require additional hardware that is specifically designed to be a USB host - and that is where the USB host shield comes in. It has a chip that is designed specially to be a USB host so you can plug a device in to it.

None of the chips on the Uno are designed to be a host. They just don't have the power.


Leonardo (32u4): ways to brick it programmatically When the Leonardo was introduced, I think, I've read some articles about being cautious to do some things, that could cause it to not load any new sketches any more, so one has to rewrite the bootloader. Because I plan to use power-saving options, e.g. to disable unused hardware components like USB port, I fear to do something wrong.

One Leonardo-delicacy I've found so far:

if interrupts are disabled, uploading new sketches fails unless one presses the Reset button as soon as the Arduino IDE is showing "Uploading..."

What stuff (except of the usual hardware-related thinks like connecting output-configured pins to fixed potentials) could damage the controller or require to reflash the Leonardo with a fresh bootloader?

If you upload a program that changes the speed of the USB core it would be almost bricked. What would happen is this:

Power on, boot loader starts, USB device enumerated on PC.
A few second later program start, USB core speed changed, USB device disappears from PC

The issue here is that not only do you have to hit reset to program, after the reset you have to quickly select the right com port and then upload before the program starts.

The Redbearlab Blend Micro requires a USB core speed to be set in the user program. In their setup instructions there is a step to edit the Arduino main.cpp and add a section to do so. If this step is missed, the above problem happens.


Why doesn't the time update? I am making an arduino clock/alarm. I use an LCD screen to display the time.

void loop(){
    static unsigned long timing=micros();
    if (mode == 0) {//mode 0 is when the time should show
        timing=countTime(timing);
        writeTime(minutes, hours);//display time
  }
}
  unsigned long countTime(unsigned long timing){
            if (micros() - timing >= 59946970) {
              return timing += 59946970;//more precise because Arduino timing is not perfect
              minutes++;

    }
        else{

         return timing;
        }

      }

    void writeTime(int minute, int hour) {
      lcd.setCursor(6, 1);
      if (minute >= 60) {
        minute = 0;
        hour++;
      }
      if (hour >= 24) {
        hour = 0;
      }
      if (minute < 10) {

        if (hour < 10) {
          lcd.print(String("0") + hour + ":" + "0" + minute);
        }
        else {
          lcd.print(hour + String(":") + "0" + minute);
        }
      }
      else {
        if (hour < 10) {
          lcd.print(String("0") + hour + ":" + minute);
        }
        else {
          lcd.print(hour + String(":") + minute); //possibly split if problems arise
        }

      }

  }

I used to do all this within the loop, but decided to make it separate. Why isn't this code working?

This statement:

static unsigned long timing=micros();

...only gives it an initial value.  It is not executed during loop.  These kinds of variables should be assigned an initial value in an executable section, perhaps when the alarm time is set.

This requires the definition to be pulled out, to the file scope:

static unsigned long timing;

void loop(){
    if (mode == 0) {//mode 0 is when the time should show
        timing=countTime(timing);

Here, the static keyword has a different meaning, although I usually use it to reduce the chances of colliding with other global variable names.

Make sure to give it an initial value in executable code somewhere:

void setup()
{
  ...
  timing = millis();  // Just once?  When the alarm is set?
}

... and update it as you do in countTime.

UPDATE  It's not clear from your snippet as to when the timing variable should be initialized, so I originally avoided addressing that.  If it is really initialized just once, at program startup, you can set it in setup.  Otherwise, it should be set when the initial timing value is finally known.


Send Processing color data into Arduino I am trying to send color() data from Processing to Arduino.

Here is my code from Processing:

import processing.serial.*;
Serial myPort;

void setup(){
  myPort = new Serial(this, Serial.list()[7], 9600);
}

void draw(){
  color[] c1 = {color(99,0,0),color(255,0,0) };
  for (int i = 0; i < c1.length; i++ ){
    int value = int(red(c1[0]));
    myPort.write(value);
    println(value);
    delay(2000);
  }
}

It sends the 99.0 data to Arduino. Here is the Arduino code for getting:

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

void loop(){
  while(Serial.available() > 0){
    int recieved = Serial.read();
      Serial.print(recieved);
    }
}

The problem is when Arduino receive data it doesn't take one by one. When i watch Arduino serial monitor, the data comes at different chunks like, 9...99...999..9.. etc.

I am trying to send several color info from Processing into arduino, it might be a long array of value. What is the best way to achieve this?

The 'best' solution depends on many things, your skill, the performance of the system, and the other tasks it needs to do in the available time. There are some examples of doing data transfer between Processing and the Arduino in the Arduino example programs. So it is worth looking through them.

There seems to be some inconsistencies in your question.

You wrote "It sends the 99.0 data to Arduino", which has a decimal point.

Yet the code is printing an int i.e.

int value = int(red(c1[0]));
myPort.write(value);

Further, the processing code only looks at the red component of c1[0]:

int value = int(red(c1[0]));

so it can only send a sequence of '9'. So that looks like a bug.

There are a few basic strategies to write data that can be easily read. Two popular ways are:

send fixed length messages, or prefix a message with the size of the
data, and have a fixed format of data. For example, use a one byte
count to say how many colours are being sent, then send three bytes,
in the same order, for each colour
use non-data bytes to separate the data. For example use a ','
between R, G or B and '\n' to mark the end of the data. To keep
things simple, never use those values as data values. That is pretty
much how programming languages work. It is much more complex to read
than fixed format data, but can give more flexibility.

Data is often sent as printable characters (e.g. 173 would be three bytes havig the ASCII values '1', '7', '3'). If it is fixed format, it would always be three bytes. For your purposes, I'd probably send each data byte as two hex characters (ASCII '0' to '9' and 'A' to 'F'. This is slightly more complex than pure binary. However it is fixed format, and more importantly it is easier to test by hand using the Arduino serial monitor, you can just type stuff and it is relatively easy to do.

Pure binary data is much more difficult to fully test, and often relies on a piece of software which also needs testing.

Summary: There are a couple of ways, it is hard to say which is best. For simplicity try to make it simple by being fixed format.


PWM generation using Registers I'm using the Registers of the Arduino micro to get a signal for Electronic Speed Controllers (ESC) for brushless motors.
As far as I read, ESCs interpret everything they can, while just ignoring too fast update rates. If somebody knows better, this would be a great time to yell.

The goal is to get a digital signal, where a timespan between 1 and 2 ms is HIGH and the rest low. Ideally I want this at 50-400Hz, since 488Hz is the fastest possible frequency, and 50 Hz the standard Servo frequency.

I try to use Phase Correct Mode to count up and down continuously. As the value in the counter reaches my set OCRnx on the way up, it sets the output pin LOW, as it reaches the same value on the way down, after reaching TOP(value), it sets the output HIGH. In ATmega documentation terms, this is NON-inverted Phase-Correct-PWM.

So I set the Registers DDR (to set the pin as output), TCCR1A and TCCR1B and ICR1 (TOPvalue = between 20000 and 2500).

Now using OCR1A = 1000 should give me a pulse width of 1000ms. This is the expected or target behaviour.

My testing code is:

// using a 16-bit timer to generate PWM signals for ESCs

// Phase Correct Mode counts from Bottom to Top and back to Bottom
// with a prescaler of 8
// motor signal (OCRnx) uses values of 1000 (idle) - 2000 (max)
// which directly corresponds to microseconds HIGH-time
// setting the range to (BOTTOM) 0 - TOPvalue sets the frequency

// two important formulas are:
// frequency(PWM) = F_CPU / (2*Prescalar*TOPvalue)
//
// PulseWidth [s] = High-tick-count / (F_CPU/Prescalar)
// High-tick-count = 2 * OCR-value

// n = number of timer (1,3)
// x = A,B,C

#include "Arduino.h"
// #include <Arduino.h>
// #define DEBUG
// #include <Moto.h>

#define PRESCALAR 8
#define PWM_FREQUENCY 50
#define TOP_VALUE F_CPU/(2*PRESCALAR*PWM_FREQUENCY)

uint16_t dutytime = 1000; // this gives idle throttle signal

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

  // TIMER 1
  // TIMSK1 = 0; // disable Interrupts for timer1
  DDRB |= (1<<DDB5); // D9 Output
  DDRC |= (1<<DDC6); // D5 Output

  // set 1000ms to start motors in idle mode
  OCR1A = 1000L;
  OCR3A = 1000L;

  // bits 7,5,3 PWM Output on pins A,B,C respectively
  // bits 1,0 WGM_1,0: phase correction mode
  // TCCR1A |= B10000010; // in hex: 0xAA for all 3 = B 1010 1010
  TCCR1A |= (1<<COM1A1)|(1<<WGM11);
  // bit 4,3 WGM_3,2: phase correction mode
  // bits 2,1,0 Prescalar: 8
  // TCCR1B |= B00010010; // in hex: 0x12; B 0001 0010
  TCCR1B |= (1<<WGM13)|(1<<CS11);
  ICR1 = TOP_VALUE;

  // TIMER 3
  // TIMSK3 = 0; // disable Interrupts for timer3
  // bit 7 PWM Output on pin A
  // bits 1,0 WGM_1,0: phase correction mode
  TCCR3A |= B10000010; // in hex: 0x82; // B 1000 0010
  // bit 4,3 WGM_3,2: phase correction mode
  // bits 2,1,0 Prescalar: 8
  TCCR3B |= B00010010; // in hex: 0x12; B 0001 0010
  ICR3 = TOP_VALUE; // TOPvalue = 2048

}//setup

void loop(void) {

  // Serial.println(TOP_VALUE);
  // delay(500);
  while (dutytime < 2000) {
    dutytime += 150;
    OCR1A = dutytime;
    OCR3A = dutytime;
    Serial.println(dutytime);
    delay(1500);
  }
  while (dutytime > 1000) {
    dutytime -= 150;
    OCR1A = dutytime;
    OCR3A = dutytime;
    Serial.println(dutytime);
    delay(1500);
  }

}//loop

I repeated the settings for timer3 to get something to compare to. Both do give the same: if i delete the loop and just write loop{} nothing happens. The pins are high and seem to stay so. With the while loops activated, my multimeter gives me 1Hz (which are the changes of course) and between 99.9% duty cycle and 96%.
An led, which i connected to it blinks every second a very short time.

What am I doing wrong?

What I did wrong was using |= instead of = . Apparently Arduino set some of these Bits on start, which didn't change.
Now it works like a charm and I added a frequency choice, which works for at least 50,200,400,488 Hz. Everything in between should work aswell!

Working testcode for timer1 with serial input of HIGH-time:

#define PRESCALAR 8
#define PWM_FREQUENCY 50
#define TOP_VALUE F_CPU/(2*PRESCALAR*PWM_FREQUENCY)

uint16_t dutytime = 1000; // this gives idle throttle signal

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

  // TIMER 1
  DDRB |= (1<<DDB5); // D9 Output

  // set 1000ms to start motors in idle mode
  OCR1A = 1000L;

  // bits 7,5,3 PWM Output on pins A,B,C respectively (COMnx1)
  // bits 1,0 WGM1(1,0): phase correction mode
  TCCR1A = B10000010; // in hex: 0xAA for all 3 = B 1010 1010
  // bit 4,3 WGM_3,2: phase correction mode
  // bits 2,1,0 Prescalar: 8
  TCCR1B = B00010010; // in hex: 0x12; B 0001 0010
  ICR1 = TOP_VALUE;
}//setup

void loop(void) {
  // Serial.println(TOP_VALUE);
  dutytime = serial_input();
  if (dutytime) {
    OCR1A = dutytime;
  }
  delay(500);
}//loop

float serial_input() {
  double num = 0;
  while(Serial.available()) {
    delay(2);
    char ser = Serial.read();
    if(isDigit(ser)) {
      num = (num*10)+(ser-48);
    }else{ break; }
  }
  if (num) {Serial.println(num);}
  return num;
}


Why is the constrain function used after the map function? I am reading some sample code and they use this method of mapping data from IR sensors:

  sensor1 = analogRead(0);
  adj_1 = map(sensor1, s1_min, s1_max, 0, 255);
  adj_1 = constrain(adj_1, 0, 255);

What is the point of using constrain here if adj_1 is already getting a value 0-255 from the map function?

From the official Arduino site:

  [The map function] does not constrain values to within the range, because out-of-range values are sometimes intended and useful. The constrain() function may be used either before or after this function, if limits to the ranges are desired.

EDIT: Example.

You can try this by yourself with this code:

int val = 20;
val = map(val, 0, 10, 0, 100);

Although you set the upper bound of the value's range to 10, you passed an higher value than that and the function will linearly map it accordingly, resulting in an output of 200.


Fading the brightness of LEDs using MAX7219 and PWM I am doing a project with bi-color led matrix 8x8 and MAX7219 as the LED driver. I want to implement a fading effect on the LEDs, like mixing the two colors by varying the individual duty cycles.

My idea is the use of the Iset parameter; I would connect the PWM pin from Arduino through the Rset resistor and feed that into the Iset of the MAX7129 instead of 5V supply. Please suggest whether or not this is possible, if not what can be the alternative approach?

This is possible in two ways:

The MAX72xx has its own internal intensity control register. From the datasheet:

  Digital control of display brightness is provided by an internal pulse-width modulator [...]. The modulator scales the average segment current in 16 steps from a maximum of 31/32 down to 1/32 of the peak current set by RSET [...].

This of course requires no extra components or effort, but you are limited slightly by only a 4-bit intensity resolution. Also, there is no 'off' so you'd have to either manually blank the displays or put the ICs into shutdown mode.

Your suggested way is possible. However, the low frequency of the Arduino's PWM may lead to flickering if the MAX7219's internal segment current reference driver needs a steady voltage. You'll have to consider smoothing the PWM output through a low pass filter - the TL072/TL082 has two op-amps so you can use one for colour A and the other for colour B. I'd choose an op-amp over passive filtering because the current drawn from the Arduino will be negligible and the stability of the current into the MAX7219 will be improved.


calculating the input current I have been a bit confused about calculating the input current, so I'd be much obliged if someone could help.

Let's say that we have a potentiometer connected with an analog input as shown below. In a middle position the resistance of the potentiometer is spitted to R1 and R2.

How can I calculate the current in A0?
How much will be the current value if (R1=0, R2=Rmax), (R1=Rmax, R2=0), (R1 and R2 !=0,Rmax)?

 5V --------
           |
           R1
           |
 A0 --------
           |
           R2
           |
          GND

When reading an analog voltage an analog pin has a very high resistance - usually very very much higher than the resistance of any potentiometer used, and input current to A0 can be regarded as zero for practical purposes.

For practical purposes the current drain from the supply will be that which flows from 5V to ground via R1 & R2.
I = V/R = 5V/(R1  + R2)

As for a potentiometer the sum of R1 + R2 is constant, the position of the pot-wiper makes no difference to current draw.

eg 10k pot. I_supply  = V/r = 5V/10K = 0.5 mA.
An I_A0 ~= 0

The upper value of a potentiometer which should be used for an analog input is covered by the uC (microcontroller) data sheet. The key parameter is uC input bias currents flowing in the potentiometer and causing small voltages which affect the analog reading. A rule of thumb is to keep such voltages under about one LSB (least significant bit) of the ADC.


IR Remote with Arduino I want to build a remote with Arduino Nano. I have viewed many tutorials in the web, but I don't have the IR Receiver (TSOP1740). Is there any way to use Jjust an IR Led as the receiver?

No, you can't use just an IR LED as the receiver.  While it is true that an IR LED can also be an IR receiver the voltages it generates are really really small. So you would need an amplification circuit. On top of that the TSOP1740 includes a band-pass filter to isolate the carrier frequency of the transmitted signal from the background light, which you would also need to implement.

So yes, while you could use an IR LED as a receiver, you need a large amount of support circuitry with it (which takes expertise not relevant to this website) to get it to do anything useful.


Many "expected `)' before ';' token" errors As the title suggests, I have many "expected `)' before ';' token" errors. The issue is, I have this stuff in. So now I am confused, why am I getting this if the things are there.

I am new here and had an issue with adding code, so here is the pastebin link to it: http://pastebin.com/4WXxsXkB

And here is the the pastebin link to the error:
http://pastebin.com/QyehP86M

Does anyone understand how this could happen?

You have two #define statements at the top of your code

#define trigPin 3;
#define echoPin 2;

The way #define works is that it replaces every instance of the name with everything after it on the line so trigPin is being replaced with 3; as opposed to 3 as intended.

Fixing this should solve some of your problems.


I want to code a depth sensor for arduino I want to code a depth sensor for a little sub that i am working on. I want it to submerge to a any certain depth  for example 2ft. The speed of the motor is to increase by 5 until it reaches the set point given. The problem that I am facing is: whenever it reaches the set example point of 2ft the motor turns off and the sub resurfaces to the top and doesn't hold the depth .
What I want is that for whatever speed the motor is at for 2ft depth, to maintain its speed and keep the sub submerge at 2ft.

#include <MS5837.h>
#include <Wire.h>
#include "MS5837.h"
#include <Servo.h>
MS5837 sensor;
Servo vertical_thruster;

float x;
float error;
int pwm = 1525;
float currentdepth = sensor.depth();
float recquireddepth = -0.4;  //  set depth u wish to maintain in meters

void setup() {
      Serial.begin(9600);
     vertical_thruster.attach(6);
     vertical_thruster.writeMicroseconds(1500);
 /////////////////////////////////////////////Bar 30 Configuration ////////////////////////////////////////
  Serial.println("Starting");
  Wire.begin();
 while (!sensor.init()) {
    Serial.println("Init failed!");
    Serial.println("Are SDA/SCL connected correctly?");
    Serial.println("Blue Robotics Bar30: White=SDA, Green=SCL");
    Serial.println("\n\n");
    delay(2000);
  }
  sensor.setModel(MS5837::MS5837_30BA);
  sensor.setFluidDensity(997); // kg/m^3 (freshwater, 1029 for seawater)
}

void loop() {

  sensor.read();
  Serial.print("Depth: ");
  Serial.print(currentdepth);
  Serial.println("m");
error = (currentdepth) - (recquireddepth) ;

if ( error!=0)
  { pwm +=5;
    vertical_thruster.writeMicroseconds(pwm+=5);
    Serial.println( pwm+=5);
    Serial.print ( " Submerging ");
  }
if ( error=0){
  vertical_thruster.writeMicroseconds(pwm);
  Serial.print ( "  At Depth");
}
else if ( error >-0){
  vertical_thruster.writeMicroseconds(1400);
  Serial.print ( "resurfacing");
  delay(1000);
}
}

Your code has several problems:

You are including the MS5837 library twice. That just doesn't pose a problem, because the library has include guards, that make sure it is only included once.
At global scope you use float currentdepth = sensor.depth();, which calls the function sensor.depth(). This will be done before the setup() function, so at that time the sensor library does not have any valid depth data. So it's useless. You can just set it to zero.
In your loop() you are doing sensor.read(), but then you are never actually getting the new depth value from the library. You are just again using currentdepth without changing it ever. You should set the variable to the new value by using currentdepth = sensor.depth(); after the sensor.read().
You are using the statement if ( error=0). Using only a single = means an assigment. So here the variable error get's set to zero and the if statement will not compare it so zero. You have to use a double =: if(error == 0).
if( error >-0): Why are you checking for error being greater than MINUS ZERO. Sure, -0 is a valid integer, but mostly senseless. Also it is questionable, if the logic is correct here, since first you check for error being different than zero. Then you check for it being zero and then (if it is not equal zero) you check for it being greater than zero. If error really happens to be greater than zero, you will first write pwm to the servo and then directly 1400, which is submerging and resurfacing directly after another in only one loop.
The whole if structure seems quite off. You should rethink the logic of the program.

That said, for reaching a set point of whatever kind it is good to use a PID controller, that will get you to the setpoint rather fast and will keep you there. A PID controller can be done in hardware or software. For implementing a software PID controller on Arduino you can use one of the various PID libraries, for example this one. Most libraries also contain examples, that show how to use them.


Is there a way to have more than 14 Output pins on arduino? Is it possible to have more than 14 output pins on the Arduino, I am working on a project in which I need to light up several LEDs individually. I only have an Arduino Uno, and I don't want to get a Mega.

A common way to expand the set of available output pins on the Arduino is to use shift registers like the 74HC595 IC (link to datasheet).

You need 3 pins to control these chips:

Clock
Latch
Data

In a program, you pass on the data one bit at a time to the shift register using the shiftOut() command, like so:

shiftOut(dataPin, clockPin, data);

With that command, you set each of the 8 outputs on the 595 IC with the 8 bits in the data variable.

With one 595, you gain 5 pins (8 on the IC, but you spend 3 to talk to it). To get more outputs, you can daisy-chain a series of 595 together, by connecting its serial-out pin, to the data pin of the next one. You also must connect together the clock and latch pins of all of the 595 ICs.

The resulting circuit (using one 595) would look like this:

The figure above was taken from this codeproject.com webpage:

Arduino Platform - Working with Shift Registers

The latch pin is used to keep the 595 outputs steady while you are shifting out data into it, like so:

digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, data);
digitalWrite(latchPin, HIGH);


Generate a ramp input with an Arduino Uno Is there anyway to generate a ramp input from an Arduino Uno? A visual depiction of the pulse I am looking for is as follows:

With other microcontrollers, I was able to use their in-built DACs, however I am aware that the Arduino UNO doesn't have any? Is there a way using PWM or analogWrite to output these type of pulses? I'm new to Arduino programming, so I'm a bit unsure. However my next guess would be to use an R-2R ladder to output this type of pulse?

A RC filter will create a slow slewrate.

simulate this circuit – Schematic created using CircuitLab

The circuit creates this signal:

A slow rising signal and a fast falling signal can be created with an extra transistor (the signal will be inverted).

simulate this circuit

For a linear rising and falling edge, a resistor network with a few digital pins is a simple solution. I think it can be created with an opamp circuit as well, but there are also special chips called "slew rate limiter".


My software serial code won't work at > 4800bps I've put together a simple software serial (send-only) implementation for use on my attiny8[45] microcontrollers.  I realize that there are more efficient USI-based implementations out there; this was mostly an educational exercise.  The code uses TIMER0 in CTC mode to time the sending of bits on an available output pin.

It works fine from 300bps up to 4800bps, but anything faster than that just results in garbage.

The complete code is at the bottom of this answer.    The following settings all work correctly:

4800bps

#define BPS 4800
#define SCALE_FLAG 1
#define SCALE_VAL 1

2400bps

#define BPS 2400
#define SCALE_FLAG 2
#define SCALE_VAL 8

1200bps

#define BPS 1200
#define SCALE_FLAG 2
#define SCALE_VAL 8

300bps

#define BPS 300
#define SCALE_FLAG 3
#define SCALE_VAL 64

While this fails:

9600bps

#define BPS 9600
#define SCALE_FLAG 1
#define SCALE_VAL 1

Because everything other than 9600bps works I'm tempted to think that my code is correct, and yet I expect that I should be able to achieve 9600bps with these microcontrollers.

Are there any obvious bugs in this code? I think that's the most likely explanation, but after poking at this for a couple of days I'm not seeing it.

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/atomic.h>
#include <string.h>

#define BPS 9600
#define SCALE_FLAG 1  // This is the value that goes in the TCCR0B register
#define SCALE_VAL 1   // This is the divisor selected by SCALE_FLAG

#define TXPORT PORTB
#define TXDDR DDRB
#define TXPIN PORTB0

#define TICKS_PER_BIT (F_CPU/BPS/SCALE_VAL)
#define mS_PER_BIT (1000000/BPS/1000)
#define uS_PER_BIT ((1000000 / BPS) - (1000 * mS_PER_BIT))

typedef struct SERIAL_PORT {
    uint8_t data;
    uint8_t index;
    uint8_t busy;
} SERIAL_PORT;

void millis_init();
uint32_t millis();

void serial_init();
void serial_putchar(char c);
void serial_print(char *s);
void serial_println(char *s);
void delay(uint32_t m);

volatile SERIAL_PORT port;
volatile uint32_t _millis,
         _micros = 1000;

int main() {
    millis_init();
    serial_init();
    while (1) {
        serial_println("hello world");
        delay(500);
    }
}

void delay(uint32_t m) {
    uint32_t t_start = millis();
    while (millis() - t_start < m);
}

void millis_init() {
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
        _millis = 0;
    }
}

uint32_t millis() {
    uint32_t x;
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
      x = _millis;
    }
    return x;
}

void serial_init() {
    DDRB |= 1<<TXPIN;       // Set TXPIN as an output
    TXPORT |= 1<<TXPIN;     // Set TXPIN high (serial idle)
    TCCR0A = 1<<WGM01;      // Select CTC mode
    TCCR0B = SCALE_FLAG;    // Set clock scaler
    OCR0A = TICKS_PER_BIT;  // Set CTC target value
    TIMSK0 |= 1<<OCIE0A;    // Enable compare match interrupt
    sei();
}

void serial_putchar(char c) {
    while (port.busy);
    port.data = c;
    port.index = 0;
    port.busy = 1;
}

void serial_print(char *s) {
    while (*s) serial_putchar(*s++);
}

void serial_println(char *s) {
    serial_print(s);
    serial_putchar('\r');
    serial_putchar('\n');
}

ISR(TIM0_COMPA_vect) {
    if (port.busy) {
        switch(port.index) {
            case 0:
                // send start bit
                TXPORT &= ~(1<<TXPIN);
                break;
            case 9:
                // send stop bit
                TXPORT |= (1<<TXPIN);
                port.busy = 0;
                break;
            default:
                // send data bit
                if (port.data & 1) {
                    TXPORT |= 1<<TXPIN;
                } else {
                    TXPORT &= ~(1<<TXPIN);
                }
                port.data >>= 1;
                break;
        }
        port.index++;
    }

    _millis += mS_PER_BIT;

    if (uS_PER_BIT > _micros) {
        _millis++;
        _micros = 1000;
    } else {
        _micros -= uS_PER_BIT;
    }
}

At 1MHz and 9600 baud, you have a total of 104 clock cycles available to run your interrupt routine in.  A quick count up of the assembly instructions generated comes to more than that (around 126 at first glance), so you can't fit it into the time.

As a result, your baud rate will actually be lower than 9600, and the chip will be completely starved of clock cycles for doing anything in your main loop.


Tone() conflicts with IRremote library (multiple definition of `__vector_7') I have just started with Arduino and C++ so I apologise if my question is very basic.
I am trying to use tone() with a passive buzzer to create a sound while also using the IRremote library for a remote. However, whenever they are used together, it gives this error:

  Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

  (.text+0x0): multiple definition of `__vector_7'

  libraries\IRremote\IRremote.cpp.o (symbol from plugin):(.text+0x0):
  first defined here

  collect2.exe: error: ld returned 1 exit status

  exit status 1

  Error compiling for board Arduino/Genuino Uno.

This is the code required to recreate this error:

#include "IRremote.h"
#include "pitches.h"
int melody[] = {NOTE_C5, NOTE_E6};

void setup() {}

void loop() {
 for (int thisNote = 0; thisNote < 2; thisNote++) {
 tone(3, melody[thisNote], 300);
}
}

Please could you advise me on how to fix this issue and if necessary, on a different library or way to create a sound or to receive IR signals?

Exactly as @MichelKeijzers wrote the issue is caused by "IRremote" using same timer as "Tone" and the solution to this problem is a little dirty.

Since Tone is included in ArduinoCore (and compiled) we can't easilly modify it so the only thing that worked for me is to modify boarddefs.h file of IRremote library. Since it's code is easilly available after downloading it using "Library Manager" included in ArduinoIDE.

In my tests I used ATmega328P settings.

Edit C:\Users\youruser\Documents\Arduino\libraries\IRremote\boarddefs.h and look for your processor number.

For ATmega328 the definition is #define IR_USE_TIMER2

I simply changed it to use #define IR_USE_TIMER1

And compilation was successfull.

Sketch uses 2746 bytes (8%) of program storage space. Maximum is 30720 bytes.
Global variables use 242 bytes (11%) of dynamic memory, leaving 1806 bytes for local variables. Maximum is 2048 bytes.

My code:

#include "IRremote.h"

#define NOTE_C5  523
#define NOTE_E6  1319

int melody[] = {NOTE_C5, NOTE_E6};

void setup() {}

void loop() {
  for (int thisNote = 0; thisNote < 2; thisNote++) {
    tone(3, melody[thisNote], 300);
  }
}


Arduino analog input protection I've been trying to find a way to protect my analog input pins (for my Leonardo and Pro micro). I'm basically using them to read an amplified piezo sensor output. The output is amplified because I'm using it to measure very low signal (heartbeats). The normal level of the sensor's output doesn't exceed 5V when I'm measuring heartbeats or chest movement, yet when the sensor is moved rapidly or lifted, I can expect a 5v+ voltage. I know that Arduino has an internal protection circuit, will that be enough to combat those sudden movements?
If not, I've read so many posts on this topic including this one:
http://www.thebox.myzen.co.uk/Tutorial/Protection.html

If I wanted to add a series resistor by itself as a protection will it be okay? and also, my signal is already small, wouldn't adding a resistor attenuate it even more?

Most circuits seem to have a capacitor, my signal is DC shifted upward (to avoid -ve voltage), wouldn't the capacitor remove that offset?

Finally, if I wanted to use the diode clamping diodes, which diodes should I use (i.e 1n4148 or 1n4002)?

Thank you

If you amplified with an op-amp powered by 5V then it couldn't produce more than 5V output, so that could be your solution. Failing that, I think a resistor and a couple of clamping diodes would help. The resistor is to current-limit the clamping diodes. I don't think you need to worry about dropping the voltage through the resistor because the analog input is high impedance.

I think the 1n4148 would be OK, I don't see why not.


AVR+Arduino ADC problem I  have connected a circuit to analog pin 0 in the Arduino.I have this code ,which I understand partially(online resources).The problem is that it prints nothing neither on Tera Term nor on Cool Term .Where am I mistaking ?(I am new to AVR programming).Here is the code:

  #include<stdio.h>
 void InitADC()
 {
 ADMUX=(1<<REFS0);// For Aref=AVcc;
 ADCSRA=(1<<ADEN)|(7<<ADPS0);
  }

 uint16_t ReadADC(uint8_t ch)
 {

    //Select ADC Channel ch must be 0-7
     ch=ch&0b00000111;
     ADMUX|=ch;

     //Start Single conversion

     ADCSRA|=(1<<ADSC);

      //Wait for conversion to complete
      while(!(ADCSRA & (1<<ADIF)));

      //Clear ADIF by writing one to it
      ADCSRA|=(1<<ADIF);

     return(ADC);
}

int main()

  {

uint16_t adc_value;

InitADC();

while(1)

{

  adc_value = ReadADC(0);
  printf("%d",adc_value);

  }

   return 0;

  }

Your code compiles, but as Gerben said, the printf won't do anything in its current state, as no output handlers are defined for it. Why go to all that trouble when you can do this?

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

void loop()
  {
  uint16_t adc_value;
  adc_value = analogRead (0);
  Serial.println (adc_value);
  delay (100);  // stop output spamming your monitor
  }

You could conceivably make printf work by following the tutorial here: http://playground.arduino.cc/Main/Printf

However I don't really see the point, when what I posted is much easier.

  If performance is an issue, you might want to use the "advanced" code.

That "advanced" code above doesn't give you any more performance, because is still blocks. You can do a non-blocking version easily and readably enough:

const byte adcPin = 0;  // A0

bool working;

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

  ADCSRA =  bit (ADEN);   // turn ADC on
  ADCSRA |= bit (ADPS0) |  bit (ADPS1) | bit (ADPS2);  // Prescaler of 128
  ADMUX =   bit (REFS0) | (adcPin & 0x07);  // AVcc
  }  // end of setup

void loop ()
  {
  if (!working)
    {
    bitSet (ADCSRA, ADSC);  // start a conversion
    working = true;
    }

  // the ADC clears the bit when done
  if (bit_is_clear(ADCSRA, ADSC))
    {
    int value = ADC;  // read result
    working = false;
    Serial.println (value);
    delay (500);
    }

  // do other stuff here

  }  // end of loop

Now that code (which admittedly fiddles with the registers) doesn't block so you could be doing other things during the conversion. I don't see any reason you wouldn't use that on a commercial product.

See ADC conversion on the Arduino (analogRead) for more details.


Why is there no hex file generated when I "build binary output" from the Arduino IDE? I want to obtain the .hex file from my Arduino sketch. I have followed various guides but there is no .hex file in my output folder.

How can I obtain my hex file?

Here are my preferences:

This is the contents of my output folder

Based on your setting with the URL for esp8266 package and bin file name with "...generic" I assume you want it for esp8266.

esp8266 doesn't use hex format and "Export compiled binary" creates bin. You can upload it with esptool.

For AVR boards "Export compiled binary" generates hex. You can upload it with avrdude.


Why do sketches take up so much space and memory? When I compile this sketch for the Yún:

int led = 7;

void setup() {
  pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(led, HIGH);
}

I get:

  Sketch uses 5,098 bytes (17%) of program storage space.

  Maximum is
  28,672 bytes. Global variables use 153 bytes (5%) of dynamic memory,
  leaving 2,407 bytes for local variables. Maximum is 2,560 bytes.

Even when I compile the BareMinimum sketch:

void setup() {
  // setup
}

void loop() {
  // loop
}

I get:

  Sketch uses 4,548 bytes (15%) of program storage space.

  Maximum is
  28,672 bytes. Global variables use 151 bytes (5%) of dynamic memory,
  leaving 2,409 bytes for local variables. Maximum is 2,560 bytes.

Why does a bare minimum sketch take up 15% of the program storage space allocated? And why does a very simple sketch take up 17% of the program storage space? According to the Arduino website:

  It's easy to use it all up by having lots of strings in your program.
  For example, a declaration like: char message[] = "I support the Cape
  Wind project."; puts 33 bytes into SRAM (each character takes a byte,
  plus the '\0' terminator).

However, there aren't any strings declared in either of these sketches.

It seems as if they might import or use other libraries/classes that I don't specify. Maybe it imports a system default library? Or is it something else?

Arduino compiles in a lot of standard libraries, interrupts, ... etc. For example the pinMode and digitalWrite functions use a lookup table to figure out at run time which GPIO registers to write data to. Another example is that Arduino keeps track of time, it defines some interrupts by default and all this functionality requires some space. You'll notice that if you extend the program, the foot print will only change slightly.

I personally like to program controllers with bare minimum, without "bloat", but you'll quickly enter the world of EE.SE and SO because several easy to use functions will no longer work out of the box. There are some alternative libraries for pinMode and digitalWrite that compile into a smaller footprint, but come with other disadvantages like for example static compiled pins (where led cannot be a variable, but is a constant).


Why is Arduino I2C so sensitive to RFI/EMI? I have a 2-motor robot project that uses a MP6050 for relative heading (yaw) measurements, and I'm having problems with the I2C bus when the motors are running.  I have done most of the things suggested here and elsewhere; 2.2K pullups vs default, shortest possible (3cm) I2C wires, MPU6050 as far away from the motor drivers as possible, reduced I2C clock speed to 100KHz, etc, etc (for additional details, see my blog post on the subject).

So, my question is, why is the I2C bus so sensitive to RFI/EMI, especially with 2.2K pullups to +5V?  Looking at the levels with my O'scope shows a 0-4.6V swing, so it's hard to believe that EMI-induced currents could be high enough across 2.2K to pull the 'high' level low enough to be considered a '0', so something else must be going on.  Maybe the EMI is getting into the MPU6050 output driver circuit, causing it to turn off?  If so, maybe capacitive bypasses on the I2C lines would help.  Any ideas?  Are other IMU modules less susceptible to motor driver EMI?

TIA,

Frank

Put a ground plate between your data lines and the power+signal lines used to drive the motor. A GPS ground plate is fine, see link below. You can just cut a piece of metal sheet to fit, or even use folded metal foil connected to ground. Motors are just noisy, and I2C is sensitive. Even updating a I2C LCD can cause noise. I like to use shielded wire (like for headphone- or HDMI cable) if my data lines are more than an inch long. You can shield lines with metal foil and heatshrink, but that’s a mess.

Use an opto-isolator to turn on your motors if a ground plate is not enough. If they only drive in one direction, add a catch diode and a 330pF cap to trim the noise. But they are probably most noisy when running. Good luck with that.

https://www.imnasa.com/en/ground-plate-200x64x12mm-for-gps-etc.html


Is my MQ-2 gas sensor analog or digital? I have this MQ-2 gas sensor for an Arduino Uno:

I found these two articles about how to use it:

https://create.arduino.cc/projecthub/Aritro/smoke-detection-using-mq-2-gas-sensor-79c54a
http://www.instructables.com/id/Ardunio-Smoke-And-Gas-SensorMQ-2/?ALLSTEPS

But I need to know if the sensor is analog or digital.
Also I would like to know what is the blue switch for.

This questions help me a bit:

It says that he use an analog sensor. But as this sensor is not mine I don't want to brake it or burn it.

Your sensor is analog. I have the same one. By the way, there is no chip on board, so it cannot form a digital signal ;)


Need to power Arduino Mega 2560 with 3.3V I found an LCD for my Arduino Mega 2560 that's parallel (I like that, I don't like SPI), but it works at 3.3V and isn't 5V tolerant. That's why I'd need to use level shifters, but that would use too much space and I'd like to power the microcontroller with 3.3V. But that would cause problems because the USART communication is set to be on 5V and that can't be changed.

Is there a way to power my Arduino at 3.3V? Is there an alternative Arduino for that?

Also, if there is, I'd need to have a 16MHz crystal on it. I know it's overclocking, but Gamebuino works at 16MHz on 3.3V and I would like to do the same.

Have you considered maybe using the Iteaduino MEGA2560?

The Iteaduino MEGA2560
uses the same ATmega2560 processor as the Arduino Mega 2560,
but is physically much smaller, the size of a Arduino UNO.
It has a switch to run the ATmega2560 at 3.3 V, so its I/O pins can be directly connected to 3.3 V modules.
It breaks out all the GPIO pins of the ATmega2560,
so it actually has more I/O on its connectors than the Arduino Mega 2560.

If I'm reading this right, the Iteaduino schematics and a typical Iteaduino features list
seems to say it already has a 16 MHz crystal.


How can I use Methods in digitalWrite(): digitalWrite(int, "methodHere")? When creating a piece of code to operate a 7-segment display, I ran into a problem:

The seven segment display on TinkerCad (I was using this at the time) requires you to pull down the inputs to turn a segment on, while the one that I have turns on when I pull up the inputs.

Instead of completely rewriting the code for the display that I had, I wanted to make my code more universal for if I need to use it in the future.

I cannot find a way to make the method digitalWrite(int pin, int val) work with a method that returns and int in the place of "int val"

This is the code that will not work:

int F = 11;
int G = 10;
int E = 9;
int D = 8;
int C = 7;
int DP = 6;
int B = 5;
int A = 4;
int type = 1;

 int highLow(int highOrLow)
{

  int digOutput;

  if(type = 1)
  {

    if(highOrLow = 1)
    {

      digOutput = 1;

    }
    if( highOrLow = 0)
    {

      digOutput = 0;

    }

  }
  if(type = 0)
  {

    if(highOrLow = 0)
    {

       digOutput = 0;

    }
    if( highOrLow = 2)
    {

      digOutput = 1;

    }

  }
  return digOutput;
}

void zero()
{
  digitalWrite(F, highLow(0));
  digitalWrite(G, HIGH);
  digitalWrite(E, LOW);
  digitalWrite(D, LOW);
  digitalWrite(C, LOW);
  digitalWrite(DP, HIGH);
  digitalWrite(B, LOW);
  digitalWrite(A, LOW);
}

setup
{
pinMode(F, OUTPUT);
pinMode(G, OUTPUT);
pinMode(E, OUTPUT);
pinMode(D, OUTPUT);
pinMode(C, OUTPUT);
pinMode(DP, OUTPUT);
pinMode(B, OUTPUT);
pinMode(A, OUTPUT);
zero();
}

Note : I am just using pin f to test.

Also, my etiquette is not very well defined or tested, so please keep it rather simple if you can.

If it matters, I am going to be using to using an Arduino Mega2560 produced by Elegoo.

Thanks for any help!!

In this situation it is far more efficient to use #define and conditional compilation.

// Uncomment this for tinkercad
// #define INVERTED

#ifdef INVERTED
#  define ON HIGH
#  define OFF LOW
#else
#  define ON LOW
#  define OFF HIGH
#endif

Then just use ON or OFF in place of HIGH and LOW.

digitalWrite(3, ON);

But the reason you have a problem is not because you are trying to use a function as the value to digtalWrite() - the problem is actually in your basic C syntax.

You are using the assignment operator (=) when you should be using the comparison operator (==). For example here:

if(highOrLow = 0)

you should have:

if(highOrLow == 0)


What kind of distance sensor are optimal to measure distances to surfaces at an angle to the sensor? I want to try measuring the orientation of an object by measuring the distance between a "flat" surface to the surface of the rotated object. The problem I assume is that if the surface being measured is at an angle to the distance sensors, the beamed lights from laser or infrared proximity sensors, for example, would be reflected at an angle and not return to the sensors at all.

Would this actually happen, or am I misunderstanding some properties of these sensors? Which sensors would work in this kind of application, and which sensors would not work for sure (I read from another post that ultrasonic sensors would definitely not work in this case)?
(Added a crude sketch of the problem I think is going to happen)

Using ultrasonic sensors would be a very sensible solution in your use case.
I am currently working on a similar project with a company in Denmark, where the objective is to detect cars on parking spaces. For this task, I used two of these ultrasonic sensors from DFRobot for the prototype:
https://www.dfrobot.com/product-1935.html
They were very easy and simple to setup on an Arduino UNO and worked perfectly fine even when two were sensing at once.
Though I have to mention, that they need a serial connection each, but this can be worked around using a multiplexer or a developer board with more serial connections.
I also found that the ultrasonic sensors work better than time of flight sensors in outdoor conditions. They are very robust and wont be as affected by dirt for instance.
A little speck on the lens of a ToF sensor and it will be rendered useless.
Ultrasonic sensors are also widely used in the car industry for parking aid solutions where they have to detect lots of different surfaces and be very precise in doing so.
Ultrasonic sensors are great. And yes, they can interfere with each other, but as long as you dont put them on top of one another, it should not be an issue.
You should be able to detect the distance to a trailer in two different places using ultrasonic sensors as long as the trailer is within the sensors range.


If the code used for Arduino can be embedded into a permanent , callable memory, is there a way to create an OS for Arduino that runs on call? This thought came into my mind on thinking about smartwatches.
Although those I saw on YouTube are really good, they don't seem to provide a real experience of a real smartwatch - one that has an OS embedded in it. If some code in Arduino C/c++ can be compiled into some binary code that works on being called from the flash memory (where the main program resides), is there a possibility that we will be able to make an OS for Arduino ?

An AVR-based Arduino is a poor choice for writing an "OS" in the modern sense. It's just too resource constrained. It doesn't have enough RAM, it doesn't have enough flash memory, it's too slow, it doesn't have protected memory or paging, it doesn't have video display, it doesn't have a file system, and on and on.
If you look at an Apple II, something like Apple DOS or ProDos gives you an idea of the sort of thing you can do (minus the video output.)
If you want to develop something like a smart watch an ARM processor is a much better choice. It packs a lot more performance into a small package. You might pick an ARM based Arduino, but you would be fighting against the lack of an OS, the lack of preemptive multi-tasking, etc.
As an alternative, a Raspberry Pi has just about everything you need. It doesn't have as many hardware interfacing options as an Arduino, but a LOT more processing power. Likewise, UNIX is a better choice as the basis for the OS for such a device. It is a protected memory OS that is made to run on relatively modest hardware.


Counter variable gets reset to 0 without resetting it(Mega) (Arduino Mega2560) I'm trying to test placing a counter n in a for loop, the problem is, every time it gets out and goes back to the for loop, the n is reset again, so it prints "counter: 245" every time. However, when I comment out *b++=data; and data++; it does count properly. What exactly is going on ?!

Code:

uint8_t i=0;
uint8_t buf[245];
uint8_t *b=buf,*b2=buf;
uint8_t data=10;
int n=0;

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

void loop() {
for(i=0; i<245 ;i++){
  *b++=data;
  data++;
  delay(50);
  n++;
  Serial.println(buf[i]);
  }
  data=0;
  delay(5000);
  Serial.println("counter:");
  Serial.println(n);
  delay(5000);
}

You never reset your b pointer. The first time through it works its way through the memory reserved for buf. The second time through your loop it's already at the end of that memory and you then start incrementing (and filling) past that overwriting other variables - the first of which sounds like it might be n - so *b++=data is writing data (245) to n.

You need to reset b each time you go through loop so it starts at the beginning of the array each time:

b = buf;


Turning on led every half hour How can I make my program so that every half hour LED lights on and work for 5 minutes and than go off and the process should repeat

I made code but it does not works. Can someone help me?

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

}
void loop() {
  digitalWrite(8,HIGH);
  delay(300000);
  digitalWrite(8,LOW);
  delay(1800000);

}

Test the LED: Connect it between +5v and ground with its current-limiting resistor. Make sure the cathode is connected to ground and not the other way round. Inside the plastic bubble are two tiny bits of metal. The larger one is the cathode. Does it light? If not, the LED is faulty or the resistor is too high.
Reconnect the LED to pin 8, which is physical pin #14. (In case you got confused and used physical pin 8, no harm was done - physical pin 8 is another ground!) Reduce the delay times to 1 second on, 1 second off. Again be sure to connect its cathode side to ground. Does it blink? If not, perhaps Arduino's pin 8 driver is faulty.
Try the same thing on a different pin (adjusting your code, of course). If it still doesn't blink, there is probably an issue with either the MCU chip or the power you're supplying to it. Assuming you used the board's +5v and ground in test (1.), then the power is OK and the chip is likely the cause.


How to record steps a stepper motor takes and how to rotate it backward and forward with analog input? I am trying to control a stepper motor's movements with a pressure sensor input (0 to 5 V digital). For example, if the input is 4 V then the stepper motor should move forward 4 steps. If the input is 3 V then it should come backward 1 step. Please suggest a command in Arduino to keep record of the previous sensor value and steps taken by stepper motor.

This is the code I have written for simple rotation of the motor:

const int stepPin = 8;
const int dirPin = 9;
int sensorValue=A0;
int i;

void setup() {
  Serial.begin(9600);
  pinMode(sensorValue, INPUT);
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
}

void loop() {
  sensorValue = analogRead(A0);
  float voltage = sensorValue * (5.0 / 1023.0);
  if(voltage==1) {
    digitalWrite(dirPin, HIGH);
    for(int x = 0; x < 200; x++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(5000);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(5000);
    }
    delay(1000); // One second delay
  }
  digitalWrite(dirPin, LOW);
  for(int x = 0; x < 200; x++) {
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
  }
  delay(1000);
  while(1);//only once
}

I analyzed your code written in the comment and assuming that it works I prepared a modification that should prevent the motor from moving when the sensor is pressed the same way all the time. The noise values you have to adjust yourself. Make it as low as you can.

I cannot test this code, because I don't have your hardware. Treat it as pseudo code.

#include <Stepper.h>
// change this to the number of steps on your motor
#define STEPS 200
#define NOISE 0.1

Stepper stepper(STEPS, 8, 9);
int previous = 0;
void setup() {
  // set the speed of the motor to 30 RPMs
  stepper.setSpeed(100);
}

void loop() {
  // get the sensor value
  float val = analogRead(A0);

  float difference = previous - val;

  if(difference < -NOISE || difference > NOISE)
  {
    stepper.step(val - previous);
    previous = val;
  }
}


Function generator with Arduino Nano I'm trying to convert the project here to an Arduino Nano.

I scaled the waveforms from 12 bit to 8 bit values. I replaced the analogReadResolution and analogWriteResolution calls with pinMode(10, OUTPUT) and pinMode(11, OUTPUT) and changed the two analogWrite calls to write to pins 10 and 11. Otherwise the program is unchanged.

My thinking (and this is where my poor electronics skills come into play) is that I just need a simple low pass filter to convert the PWM into the appropriate waveform (which, at startup, ought to be a sine wave on both pins). According to the article, the frequency generator tops out at 170Hz. I figure the PWM signal is going to be significantly higher than that, so I use R=3.3K and C = .1uF for my RC filter which ought to give me a -3dB at about 480Hz, but what I'm seeing on my scope is a mess. Not a stable signal at all.

This is the waveform I'm seeing on my scope:

Can someone educate me?

Update: BTW, this is the initial waveform which ought to be a sine wave.

The PWMs on pins 10 and 11 of the Arduino Nano run at 488 Hz. That's what you are seeing on the scope. The code you are using was meant for an Arduino Due, which has real digital-to-analog converters.

Edit: You can tune the PWM to run as high as F_CPU/256 by
reconfiguring the timers 1 and 2 to “fast PWM” mode, instead of phase
correct PWM, and setting their prescalers to 1 instead of 64. This
should raise the PWM frequency to 62.5 kHz, given that the Nano has
a 16 MHz clock.

The following code should do exactly this. You can put it somewhere
inside your setup(). Warning: I have not tested this code. This
will change the PWM frequency on pins 10 and 11, but also on pins 3 and
9, which share the same timers. It will probably break the tone()
Arduino function.

// Set PWM frequency to 62.5 kHz on pins 3, 9, 10 and 11.
TCCR1A = 1<<WGM10;
TCCR1B = 1<<WGM12 | 1<<CS10;
TCCR2A = 1<<WGM21 | 1<<WGM20;
TCCR2B = 1<<CS20;


I2C collision detection I have put together a system that uses multiple Arduinos and a couple of 20x4 LCD displays to monitor my PV sun tracker and a weather station.  I am using I2C to link them all together.  One of the LCDs has been modified to have a different address (0x3b) so as to not conflict with the first one (0x3f).  So far, so good.   The sun tracker shows its display on the yellow one and the weather station shows its data on the blue one.

In order to connect this together I am using the Mayhew I2C&Power devices, so one power source energizes the entire system.  I send 12 Volts on the wire, then at each node I use a 12v to 5v converter to provide power for the I2C&Power board and the Nanos.  (The anemometer on the WX needs 12V to operate so that's a plus)

Each Arduino has a unique I2C address - there is no master in the system.

I have learned to set the screen updates to be quick (take readings and do any calculations before writing to the LCD in one swell foop), and to stagger the display update timings (the WX info updates every 65050 ms (full display update) and the PV info updates every 67050 ms (4 characters) and 605550 ms (full display refresh).  I chose these (arbitrarily random) values to make it less likely that they would try to update at the same time, because when both systems try to update their respective displays at the same time it causes some very interesting results - basically wiping out one or both displays.  It works most of the time but eventually one or the other screen will get wiped out.

Question:  Is there any way to implement collision detection on the I2C bus to prevent transmitting while other devices are communicating?  Something like CSMA/CD (Carrier Sense Multiple Access with Collision Detection) on Ethernet..

Collision detection on I2C is fully supported (See I2C Multi-Master). It works basically by attempting to transmit something and reading what is being transmitted at the same time. If what is read matches what is transmitted then the transmission worked. If it didn't match then there was a collision.

It is usually performed on a per-bit basis:

If a 0 then pull the data line LOW. If a 1 then let the resistor pull the data line HIGH.
Read the data line. If you want a 1 and get a 0 then some other device is pulling the data line low for a 0.
If the value was wrong then stop your transmission and back off by a random amount. Retry again. (note: both ends may retry, so you need good random numbers).

There is no support in the Wire library for collision detection, though, so you will have to implement it yourself. Section 22.4 of the datasheet gives you more information about how to implement it.


Different Output Voltages from Same Source? I'm wondering whether it is possible to wire multiple buck converters with different voltage requirements and amperage draws to the same power source (this idea is for controlling a radio-controlled boat). Going off other related questions this seems to be possible (1, 2).
My background is in programming, not electronics, so the terminology is difficult for me to understand. I'm getting a grasp on voltage and amperage. My problem is always understanding how electricity can be "split" into different modules. In my understanding, this below would be a parallel circuit and that should be fine.

Are there any gotchas to consider with this type of circuit, or is this the totally normal way of doing things (eg. like wiring a house out of a breaker box)?
Is there a better way to do this?
This won't cause a short circuit, right?

Are there any gotchas to consider with this type of circuit, or is this the totally normal way of doing things (eg. like wiring a house out of a breaker box)?

That's a perfectly normal way of wiring it.

Is there a better way to do this?

No, it's how I'd do it.

This won't cause a short circuit, right?

Not intentionally, no. However it's always good to add a fuse or two to protect everything just in case anything untoward should happen. Especially where water is concerned.


Determine whether a variable is of an arithmetic type Is there a way to determine whether a variable is of an arithmetic type or not?

arithmetic: integer, floating point numbers, boolean values
not arithmetic: pointers, references; e.g. strings, and probably all other implementation- and user-defined types. However if someone for some reason defines typedef int myInt myInt should be considered arithmetic as well (because it is!)

In a normal C++ program I could use std::is_arithmetic<T>::value, where T is the type I need to check, but this doesn't seem to work in the Arduino environment. (Am I wrong? If it works, could someone please tell me how to use it?)

I imagine I could make a list of allowed types, e.g. as described in this answer to a similar question (I'm referring to the second option, the Alternative). But given that I don't need to exactly know the type of T I was wondering whether there is a more elegant and flexible solution...

Is there a way to determine whether a variable is of an arithmetic type or not?

no. end of the day, those are just bit pieces and it only makes sense to the computer with the right context. Another way to put it, the same bit pieces can and will mean different things under different situations.


USB device not recognised - windows 8.1 I'm a beginner with Arduino and i have acquired the Arduino UNO R3 board. i have followed the instructions on arduino website in order to install the board, however it fails and still remains as an unrecognised device.

consequently, arduino IDE reports that COM1 is not found, and the 'ports' menu is grayed out.

steps i have tried:

1) install the Arduino 1.0.5 IDE
   - the installation failes near the end when installing the arduino board
2) install the Arduino 1.5.7 BETA IDE
- the installation is successful but arduino device is still unrecognized.
3) i have tried manually installing the drivers by letting windows search in the arduino IDE installation folder/drivers/
- it reports that the best driver is already installed - "usb unrecognized device"
4) i have tried installing the drivers by manulally loading the .inf files from the IDE installation folders, and installing all the serial converter A/B/C/D in the list - all failed to install.

i have done all the above for both IDE 1.0.5 and 1.5.7b with windows installer And zipped files, under administrative rights in windows 8.1

How do i get this to work?

The issue was resolved by changing my USB cable. the cable in the kit was new and seemed to supply power to the arduino board, but windows was unable to identify the board using that cable. maybe the data wires were damaged.
 in any case, i changed the cable and everything worked smoothly.


what is welding plate? I was looking at arduino nano boards here. Description says the arduino board is without welding plate. What does it mean for the user? If I buy this product will there be any issue? I understand that this board does not come with two headers soldered and I am OK with that.

Probably a mistranslation of soldering. As far as I can tell, it just means that the headers are not soldered on.

(see https://www.aliexpress.com/store/product/Nano-V3-0-ATMEGA328P-improved-welding-plate-without-wiring-module-board/630494_32807228948.html for one with "welding plate")


Do I need to supply the 12V connection to an HDD I'm working on trying to control a hard drive with an Arduino Uno, but I'm having trouble with the power supply. From what I know, both the Molex Mate-n-Lok and the new SATA connectors both have 2 grounds, a 5V and a 12V power in. I'm wondering what the purpose of the 12V power supply is. I suspect it's used to drive the motor but I'm not sure.

Judging by my old copy of "Upgrading and repairing PCs" - which I found a quote for on Google Books - the 12V supply is for the spindle motor, and it says:

  Spindle motors, particularly on the larger form-factor drivers, can consume a great deal of 12V power.


Why are my thermistor readings backward? I'm trying to build a thermistor that will flash an LED when the temperature is above 30 C. My set-up appeared to be reporting the room temperature correctly to the Serial Monitor, but then I noticed that exposing the thermistor to a hot object causes the reported temperature to drop, whereas exposing it to a cold object causes the reported temperature to rise.

I'd built a simpler thermistor circuit earlier with a similar approach and everything seemed to function correctly. I'm not sure what I broke here:

const int WarningLED = 7;
const int Thermistor = 0;

/* Thermistor information:
 * P/N: BC2301-ND
 * MFG P/n: NTCLE100E3103JB0
 * DESC: THERMISTOR NTC 10KOHM 3977K BEAD, IDX: 1 */

int Vo; // voltage between thermistor and R1
float R1 = 10000; //10 KOHM resistor used for voltage divider
float TR; // resistance of negative temperature coefficient (NTC) thermistor
float beta;  //beta will later equal ln( TR / Rref )
float Tk, Tc, Tf;

/* Steinhart-Hart equation coefficients via data table at
 * http://www.vishay.com/docs/29049/ntcle100.pdf
 * Bead used: 3977K (refer to #9 values on Nominal R table) */
float A = 3.354016e-03,B = 2.569850e-04;
float C = 2.620131e-06,D = 6.383091e-08;

void setup() {
  pinMode(WarningLED, OUTPUT); //sets the warning LED pin as a digital output
  Serial.begin(9600);          //  setup a serial port to enable comms with the computer.
 }

void loop() {

  Vo = analogRead(Thermistor);
  Serial.print("Vo: ");
  Serial.print(Vo);
  Serial.println(" mV");

  //Voltage divider equation: R2 = R1 * [Vo / (Vi - Vo)]
  //where R2 = TR, Vi = 1023.0 :
  TR = R1 * ((float)Vo / (1023.0 - (float)Vo));
  Serial.print("Thermistor resistance: ");
  Serial.print(TR);
  Serial.println(" ohms");

  beta = log(TR/10000); // As per extended Steinhart-Hart equation,
  //  where Rref = 10,000 (refer to page 10 of the PDF linked above)
  Tk = (1.0 / (A + B*beta + C*beta*beta + D*beta*beta*beta));
  Tc = Tk - 273.15;
  Tf = (Tc * 9.0)/ 5.0 + 32.0;

  Serial.print("Temperature: ");
  Serial.print(Tk);
  Serial.print(" K; ");
  Serial.print(Tf);
  Serial.print(" F; ");
  Serial.print(Tc);
  Serial.println(" C");
  Serial.println();

  if (Tc > 30.0) digitalWrite(WarningLED, HIGH);
  else if (Tc < 30.0) digitalWrite(WarningLED, LOW);
  delay(1000);
}

On the Serial Monitor, this reports:

Vo: 550 mV
Thermistor resistance: 11627.91 ohms
Temperature: 294.74 K; 70.86 F; 21.59 C

Exposing this to a warmer temperature incorrectly reports:

Vo: 597 mV
Thermistor resistance: 14014.08 ohms
Temperature: 290.61 K; 63.43 F; 17.46 C

I notice that, among other issues, this is reporting increased resistance in the thermistor despite that I'm using an NTC, but I'm not sure why this is occurring.

Notable parts used in this circuit:

Thermistor: NTCLE100E3103JB0
R1: 10 KOHM
R2: 1 KOHM
C1 & C2: 33 nf

The voltage Vo is not the over the termistor it over R1! Change place on termistor and R1.
/Mikael


How to modify a created byte? I have created a byte for 16x2 LCD. It is basically a custom character which I will have to change later.

byte char[8]{
 B10000,
 B01000,
 B00100,
 B00010,
 B00001,
 B11000,
 B11100
};

I want to edit the third number from fourth row. So, the fourth row will become B00110 from B00010. Is this possible? Are there any alternatives for this?

Well first of all you are trying to name the variable char? which is already a keyword for the variable type of char.   But you can access it by the index of the array. Also not sure if you intended to make the array 8 bytes in length, and then only use 7, but thats what you had done in your example

//define it all at once
// byte byteArray[8] = {B10000,B01000,B00100,B00010,B00001,B11000,B11100};
//or by index
byte byteArray[8];
byteArray[0]=B10000;
byteArray[1]=B01000;
byteArray[2]=B00100;
byteArray[3]=B00010;
byteArray[4]=B00001;
byteArray[5]=B11000;
byteArray[6]=B11100;

//if you need to change one in the code elsewhere
byteArray[3]=B00110;
//or
byteArray[3]=6;
}


(SOLVED) Fast HW check: (18 digital + 4 analog to I2C ) Arduino Mini Pro + MCP23017 or STM32? Arduino Mini Pro+MCP23017 or  STM32

I want make device, which reads 17 digital buttons and 4 analog, process it somehow and send the result to I2C bus. Also there is a LED to be managed. I may want to attach some wireless too later, but I am not really sure, if I woud do it (which would need 5-6 mor digital pins). I need to update the firmware often, as it is under heavy developement just now. I should make the PCB as soon as possible, but programming can wait some time.

The PCB would have buttons and analogs on it (and MCP in the arduino case). Also lot of connectors, like I2C, programming interface and some power regulators, the LED (or maybe more of them, if there was few free pins, but it is not mandatory). The processor will be connected via wires for space reasons (and maintainability and the board may be redesined later), so only long row of soldering pads on PCB for it.

Main decision:
If I opt to Arduino, then MCP will be part of the PCB and connected to I2C bus, if I use STM32, no MPC will be present and buttons would go directly to output connector.

Making the HW is no problem for me, the logic inside is also easy (basically read all inputs, normalize analogs to some range, make some simple tests and if desired, send result over I2C. Reply to some simple I2C too.)

I have a lot of Arduino Mini Pro, but it is few legs short for the task, so I would use MCP23017 expander for 16 of that digital buttons.

I also got some these STM32
https://www.aliexpress.com/item/STM32F103C8T6-ARM-STM32-Minimum-System-Development-Board-Module-For-Arduino/32279776568.html but did not open the package yet. Anyway I want to learn to use them "sometimes soon".

Maybe it is just the kind of starter project, which I would like to do.

Now I am just not sure about the number of available pins on the STM32, on first look it have more pins, but each description I found yet states too much details about additional functions, but I got confused about the basics here. So my question is:

Can mentioned STM be easilly programed as Arduino, manage I2C communication, and still have comfortable 18+4 I/O pins free? And 23+4 I/O free?

Can mentioned STM be easilly programed as Arduino, manage I2C communication, and still have comfortable 18+4 I/O pins free? And 23+4 I/O free?

it can be programed as Arduino, manage I2C communication, and still have 18+4 I/O pins free or 23+4 I/O free.

it is only knowable to the person programming it whether it can be done easily or comfortably.


Standalone ATmega328P stops responding when RX is connected I have followed this demo and have set up a standalone ATmega328P being programmed from a Raspberry Pi via the SPI lines. I have also added a 16 MHz crystal with 22 pF capacitors, as well as I have enabled and set up I²C between the ATmega and Raspberry Pi.
I have compiled and uploaded a bunch of programs and I can confirm everything works as expected.
As you can imagine, it is quite hard debugging things without a serial connection, so I connected pin 2 of the ATmega to GPIO14 of the Raspberry Pi and pin 3 to GPIO15. At this point, when I try uploading a program, I get this:
$ avrdude -P /dev/spidev0.0 -c linuxspi -p m328p -U flash:w:build-uno/program.hex

avrdude: error: AVR device not responding
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

If I break the pin2 to GPIO14 connection, then my program gets uploaded. And if I restore the connection between the pins and open Minicom on the Raspberry Pi I see the output of my simple program:
void setup() {
  Serial.begin(9600);
}

void loop() {
  delay(1000);

  Serial.println("Echo Test");
}

$ minicom -b 9600 -o -D /dev/ttyS0

Welcome to minicom 2.7.1

OPTIONS: I18n
Compiled on Aug 13 2017, 15:25:34.
Port /dev/ttyS0, 16:50:17

Press CTRL-A Z for help on special keys

Echo Test
Echo Test
Echo Test
Echo Test

But whenever I press a button on the keyboard (inside Minicom), I notice that the ATmega gets reset. If I hold the button down the transmission of "Echo Test" seizes as it is getting reset rapidly.
How can I get serial to function properly?
Addendum:
I'm using a Raspberry Pi 4, and in raspi-config I have disabled serial login and left the serial hardware enabled.

There are two things wrong with the circuit in that demo.

There is no decoupling capacitor on the power pins. This is required to keep the power stable during opertaion.
More critically: this is being powered from 3.3V, but is being run at 16MHz. That is outside specifications. You should use an 8MHz crystal to operate at 3.3V.


Every so often ESP8266 hangs... WifiClient seems to be at fault This code works fine without any freezes:

#include <ESP8266WiFi.h>
#include <Servo.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>

Servo turn;

ESP8266WiFiMulti wifiMulti;

const char* host = "192.168.1.148";
WiFiClient client;

int turnPos = 90;
unsigned long ts = 0;

void setup() {
  startWiFi();
  turn.attach(14);
  turn.write(90);
}

void loop() {

  if (millis() - ts > 500 && millis() - ts < 1000) {
    turnPos = 160;
  }
  else if (millis() - ts >= 1000) {
    ts = millis();
  }
  else {
    turnPos = 20;
  }

  /*if (client.connected()) {
    }
    else {
    if (!client.connect(host, 3000)) {
    }
    }*/

  turn.write(turnPos);
  yield();
}

void startWiFi() {
  wifiMulti.addAP("DVW3201BE8", "###");   // password is filled in on mny version
  while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
    delay(250);
    Serial.print('.');
  }
}

While this code (with the wificlient bit commented out) freezes every so often:

#include <ESP8266WiFi.h>
#include <Servo.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>

Servo turn;

ESP8266WiFiMulti wifiMulti;

const char* host = "192.168.1.148";
WiFiClient client;

int turnPos = 90;
unsigned long ts = 0;

void setup() {
  startWiFi();
  turn.attach(14);
  turn.write(90);
}

void loop() {

  if (millis() - ts > 500 && millis() - ts < 1000) {
    turnPos = 160;
  }
  else if (millis() - ts >= 1000) {
    ts = millis();
  }
  else {
    turnPos = 20;
  }

  if (client.connected()) {
    }
    else {
    if (!client.connect(host, 3000)) {
    }
    }

  turn.write(turnPos);
  yield();
}

void startWiFi() {
  wifiMulti.addAP("DVW3201BE8", "###");   // password is filled in on mny version
  while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
    delay(250);
    Serial.print('.');
  }
}

Only difference is in the working one the WifiClient bit of code is commented out.   How would WifiClient cause this problem?

It is a bug and it was fixed in Arduino esp8266 core package 2.4.2 published 2 days ago.

see first line in ESP8266WiFi section of the changes list

  2.4.2 ESP8266WiFi:
  Fix memory leak when reusing WiFiClient object (#4497, #4516, #4549)


What is the best way I can detect if a ping pong ball has hit the ping pong table? The ultimate goal is to track points, which in the case ping pong, is how many times the ball has touched the table.
My concerns are with how light the ball and therefore the impact on the table will be. Is this too light for something like a vibration sensor to register?
Would you imagine the sensor working better on the paddles or the table?
I'm open to other suggestions on more reliable ways to track other than vibration. Definitely new to arduino.

Having played ping-pong (badly) I think a microphone would be able to count ball/table impacts quite well. The 'click' sound is much higher than that of hitting the paddle, so you might be able to differentiate on that basis. You might consider a two microphone/transducer arrangement- one coupled to the table and one not touching the table. If you get a simultaneous signal on both, the ball has hit the table. If you get only one signal (from the not-touching microphone) then the ball has hit a paddle. This also gives you the option of getting some timing information.


changed behaviour in I2C LCD I reinstalled a previously working sketch to my UNO and now the behaviour of the lcd has changed.

Previously this example worked perfectly:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup()
{
  lcd.init();                      // initialize the lcd

  // Print a message to the LCD.
  lcd.backlight();
  lcd.print("Hello, world!");
}

void loop()
{
}

Now it only displays the very first character 'H'

This version does work though:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup()
{
  lcd.init();                      // initialize the lcd

  // Print a message to the LCD.
  lcd.backlight();
  lcd.print("H");
  lcd.print("e");
  lcd.print("l");
  lcd.print("l");
  lcd.print("o");
  lcd.print(" ");
  lcd.print("W");
  lcd.print("o");
  lcd.print("r");
  lcd.print("l");
  lcd.print("d");
}

void loop()
{
}

Can anyone shed me any light what is the reason of this change in behaviour and how to solve it?

Running version 1.8.3 on a W7pro PC

There seems to be an incompatibility between recent versions of the IDE and the library I was using.

Installing the latest version of the library from GitHub and replacing the lcd.init() command with lcd.begin() in my sketches solved the problem.


Weird output from chained 74HC595 shift registers EDIT 4/2/18: The Arduino tutorial schematics have been corrected! See https://github.com/arduino/Arduino/issues/6433 for that issue.

I have a project where I am trying to load a 16-bit number onto an EEPROM using an Arduino hooked up to two 74HC595 Shift registers.

I'm loosely following this Arduino tutorial: https://www.arduino.cc/en/Tutorial/ShiftOut, but I'm getting unexpected outputs depending on the number I try to load into the register. I've reduced everything to as simple a setup as I can, and have spent several hours trying to figure out what the heck is going wrong... obviously to no avail.

Here is the schematic - with the exception that I moved the capacitor off of ST_CP (why would they put that in the tutorial?) to between power and ground:

Here is my code:

#define SHIFT_DATA 2
#define SHIFT_CLK 3
#define SHIFT_LATCH 4

void setup() {
  pinMode(SHIFT_DATA, OUTPUT);
  pinMode(SHIFT_CLK, OUTPUT);
  pinMode(SHIFT_LATCH, OUTPUT);

  int address = 0b1111111111111111;  // Case 1
//int address = 0b0000000000000000;  // Case 2
//int address = 0b0101010101010101;  // Case 3
//int address = 0b1010101010101010;  // Case 4
//int address = 0b0101100110101110;  // Case 5

  shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, (address >> 8)); // Load first 8 bits
  shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, address);        // Load second 8 bits

  digitalWrite(SHIFT_LATCH, LOW);
  digitalWrite(SHIFT_LATCH, HIGH);
  digitalWrite(SHIFT_LATCH, LOW);
}

void loop() {
  // none
}

Here is a picture of my breadboard setup with Case 1 loaded:

And here follows my test cases.

All 1's (1111111111111111). Looks good.
All 0's (0000000000000000). Looks good.
Repeated 01's (0101010101010101). Looks good.
Repeated 10's (1010101010101010). Output: 1010101000000000. First 8 bits match, last 8 are zeros. Huh?
Random sequence (0101100110101110). Output: all over the place. Initially the first 8 bits match as in Case 4, but on repeated resets of the Arduino the output changes, with some weird momentary flickering going on for some of the LEDs. If I press it enough times I can get it back to the initial output, but never what I expect. I am completely stumped. Here is an animated gif of this behavior running on the breadboard: http://i.imgur.com/KEwpSXe.gifv.

What could my problem be? I assume it's something very simple and I'm being an idiot.

You should change your capacitors.

You only have 0.1µF instead of 1µF for the bulk capacitor (which really wants to be 10µF). In addition you should add 0.1µF (100nF) capacitors directly across the power pins of each chip:


Placing decoupling capacitors when building an Arduino PCB with Atmega328-PU I have previously asked this question:

Custom build of arduino on a pcb

And thanks to the answer by Majenco I have learned that my circuit works a lot better when adding a capacitor. For example I am using the NRF24L01 and it is much more stable when using a capacitor. I am placing the capacitor for now next to the power supply like this:

Right now I am running this on a breadboard. The Atmega328 chip is very cheap compared to the arduino uno board; therefore, I will like to continue building my projects based on the atmega328P-PU chip.

Anyways before printing the PCB based on the Atmega328P-PU chip, where should I place the capacitors in order to reduce the most noise? The capacitors are very cheap and making one good design will enable me for all my future designs to be based from this one.

From researching on the internet I see a lot of different examples. Everyone uses different capacitance sizes. For example I have found this:

I got that from this link: https://www.autodesk.com/products/eagle/blog/what-are-decoupling-capacitors/

On other places they say to place the capacitance closest to the pins such as from this video. If that is true should I just place one capacitor on pins 7 and 8. Lastly the other capacitor on pins 20 and 22?

I do not mind soldering extra pins knowing my circuit will have the best performance.

The Autodesk link explains it very well.

You should place small/fast decoupling capacitors (0.1uF) close to the power pins of your on-board ICs to deal with local spikes in power consumption of those devices.

Place a larger/slower decoupling capacitor (1uF or larger, depending on many factors such as distance of the power supply from the board and expected power consumption) somewhere on the board to deal with varying loads and ripples in your power supply.

This has been common practice at least since I’ve started with electronics about 40 years ago (and probably much longer).


how to increase the delay factor of DHT11? There is no compiler error but output is showing timeout error.
as per as the instruction given in
https://github.com/RobTillaart/Arduino/issues/61

it says to increase the timeout factor but i did not found the constraints which were asked to be changed.

The DHT11 and DHT22 used to be cheap and easy to use humidity and temperature sensors when they were used together with an Arduino Uno.

But things have changed.

They are not accurate and can become totally inaccurate with certain
gasses or fumes.
It turned out, that the most used DHT libraries have
a serious bug that creates a shortcut in the datasignal.
This was no problem with the Arduino Uno, which can output
40 mA with a pin. The newer processors have problems with
that shortcut.
In 2018 the DHT11 seems to behave differently,
the internal controller has probably changed.
Because the communication with the sensors requires accurate timing,
the interrupts are turned off temporarily. That was no problem
with the slow Arduino Uno, but it is not normal with
a faster processor.
Some libraries use a timeout with a loop or with clock cycles.
That worked well with the Arduino Uno,
but it is not always reliable with newer processors.

In 2018, all the DHT libraries for the ESP8266 and ESP32 have issues with the DHT11 and DHT22.

Since the sensors are not very accurate anyway, it is best to stay away from all the troubles and avoid them. There are a number of good humidity sensors with I2C interface.


LCD not doing anything I just bought an LCD. I connected everything as explained in this sheet.

This is the code I am using:

#define RST 3
#define CE 2
#define DC 4
#define DIN 6
#define CLK 5

void LcdWriteCmd(byte cmd) {
  digitalWrite(DC, HIGH); //DC pin is low for commands
  digitalWrite(CE, HIGH);
  shiftOut(DIN, CLK, MSBFIRST, cmd); //transmit serial data
  digitalWrite(CE, LOW);
}

void setup() {
  pinMode(RST, OUTPUT);
  pinMode(CE, OUTPUT);
  pinMode(DC, OUTPUT);
  pinMode(DIN, OUTPUT);
  pinMode(CLK, OUTPUT);
  digitalWrite(RST, LOW);
  digitalWrite(RST, HIGH);
  LcdWriteCmd(0xAE); // LCD set display enabled
  LcdWriteCmd(0x21); // LCD set power COntrol
  LcdWriteCmd(0x14); // LCD bias mode 1:40
  LcdWriteCmd(0xA2); // LCD basic commands
  LcdWriteCmd(0xA9); // LCD all segments on
}

void loop() {
}

The commands I used are in the command table of this sheet. (page 12)
It is supposed to turn all pixels on now. However nothing happens. All pixels are staying off.

Can you see a problem?

I am not so sure the command that you used to turn all pixels on is right. It might say it in the document but you should try to manually turn a couple of pixels on yourself. check the link bellow if you need more assistance with LCDs.

Also be sure that you connected some power and a potentiometer to the contrast pin and/or backlight of the LCD.

https://www.youtube.com/watch?v=dZZynJLmTn8


problems with Blue Pill (stm32f103c8t6) direct register manipulation I'm trying to access registers but I keep getting the "was not declared in this scope" error message.
I'm currently using the STM32F1xx boards from http://dan.drown.org/stm32duino/package_STM32duino_index.json
The board package does not seam to recognize any of the registers from the reference manual, mostly trying to access the ADC registers such as 'ADC_CR2'. Does anyone know where I can find the register names which works in the Arduino IDE?

you need to use something like this:
ADC1->CR2 = ... ;

note 2 things:

you need to use ADC1, ADC2 ... to access the registers. not just ADC.
you need to use arrow (->) operator to access the registers

and you may need to include the header file, something like this :
#include <stm32f030x6.h>

find the proper header file for your MCU. (it's not the same as stm32f1xx, but if proper definitions are made somewhere, it may also work)


5V 1A vs 5V 5A power supply for 6 LED + Arduino If I want to power up 6 normal 3mm LED with the appropriate series limiting resistor, do I need the 5V with 1A or 5A power supply? Same goes to the Arduino, if I want to power it externally, do I go for the 1A or 5A?

Depending on your led, it will draw 10 to 20mA for a standard led. Thats 0.010 to 0.020A. Multiply this by 6 and you see that a 1A power supply will be enough.

Your arduino, when driving those leds, will also use a few mA. So you can power everything with a 1A power supply.


Adafruit OLED 7 Pin Display - Abbreviations I can't remember for the life of me how exactly I set up this screen in previous models, partially because the references I'm using in my code have different names from the pins on the Adafruit display.
My code identifies the following digital pins for the following display pins:
OLED_MOSI = 12
OLED_CLK = 11
OLED_DC = 10
OLED_CS = 8
OLED_RESET = 9

My Arduino is then attached from the following pins to those labelled on the OLED display as"
12 -> SDA
11 -> SCK
10 -> DC
8 -> CS
9 -> RES
5V -> VDD
GND -> GND

In other words, I am interpreting the following as being equivalent:
RES = RESET
SCK = SCK
MOSI = SDA

Is there anything within the information I've provided that is wrong / may cause the screen to malfunction?
Thank you very much in advance.

DC selects between Data and Commands.
CS is the Chip Select
SDA is the Serial DAta.
SCL is the Serial CLock.

These four together form what the documentation calls the "4-wire serial interface". It's not quite like SPI, owing to the presence of the DC pin (which is why it doesn't use SPI terminology), but close enough that SPI can be used to communicate with it.
In SPI the pin that sends data from the Arduino to the slave is known as the MOSI - Master Out Slave In.  Some microcontrollers also call this SDO - Serial Data Out, where it's "out from the master's perspective".


and gate based on truth table I have to code in arduino the logic gates based on the truth table with two inputs. I searched for some examples, however all that I found is using && to compared them using only onf if else condition. What I need is to do it using all the possible cases. This is what I have, however only the last condition is working. I ask you please clarify to me what concept I am not understanding well, or what is wrong in my logic. Thank you.

  const int p2  = 2;  //Ground G
  const int p13 = 13; //Input A
  const int p15 = 15; //Input B

  void setup() {
    // put your setup code here, to run once:
    pinMode(p2,   OUTPUT);
    pinMode(p13,  INPUT_PULLUP);
    pinMode(p15,  INPUT_PULLUP);
  }
void loop() {
  // put your main code here, to run repeatedly:
  if ( digitalRead(p13) == 0 && digitalRead(p15) == 0 ){
    digitalWrite(p2, HIGH);
  }

  if( digitalRead(p13) == 0 && digitalRead(p15) == 1 ) {
    digitalWrite(p2, LOW);
  }

  if( digitalRead(p13) == 1 && digitalRead(p15) == 0 ) {
    digitalWrite(p2, LOW);
  }

  if( digitalRead(p13)== 1 && digitalRead(p15) == 1) {
    digitalWrite(p2, LOW);
  }

}

Your whole code can be replaced with one line:

digitalWrite(output_pin, digitalRead(inputA_pin) && digitalRead(inputB_pin));

That is, write out the results of a boolean AND on the state of the two inputs.


Why is the piezo buzzer not making any sound? My ciruit:

My code:

// Pin 13 has a LED connected on most Arduino boards.
// give it a name:
int led = 13;
const int buttonPin = 2;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

// the loop routine runs over and over again forever:
void loop()
{
  bool buttonState = digitalRead(buttonPin);
  while (buttonState == LOW)
  {
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
   delay(1000);               // wait for a second
   digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
   delay(1000);               // wait for a second
   tone(12,260);
  {
 }
  }
}

What I wish to do, is that when the button is pressed, and the Led's start to blink, I want the piezo buzzer to make a sound. I have never worked with them before so I am having troubles getting results. Is it that the setup is wrong or the code needs extra lines than just the tone(12,260); that I added?

Both the code and the circuit have problems.

In the code:

• If the while (buttonState == LOW) loop is ever entered, it will never be left, because buttonState, the controlling variable, does not change within the loop.

The simplest fix is to remove the line bool buttonState = digitalRead(buttonPin); and replace while (buttonState == LOW) with while (!digitalRead(buttonPin)), which says to loop while digitalRead(buttonPin) is not true; ie, while it is false, or low.

• The empty braces, { } at the end of the while loop are superfluous and should be deleted.

In the circuit diagram:

• Neither of the leads of the buzzer is attached to the Arduino circuit, so it won't make any sound.  Note, tone(12,260); tells the Arduino to use pin 12 for tone output.

To fix this problem, run a wire from pin 12 to one side of the buzzer, and a wire to ground for the other side of the buzzer.

• A blue LED in series with a red LED might or might not turn on when supplied with 5 V.  For example, if the red LED takes 1.8 V and the blue LED takes 3.3 V to turn on, the 5.1 V total is too high to be turned on by 5 V signals.  Remove one of the two LEDs, and move the wires to the other LED to complete a circuit.


Arduino Due SPI clock pauses each octet I'm trying to communicate with SPI slave using Arduino DUE as master. Device requires commands to be 32 bit wide, SPI mode 3.

I've ran the minimum code (using Arduino IDE 1.8.12) to send some 32 bit wide nonsense, and I've noticed that clock stops for a while after each octet is sent. Also the pause after CS goes LOW is too long.

What is the best practice to achieve a clean 32 bit wide transmission?

#include <SPI.h>

const int cs_pin = 25;
const SPISettings spi_settings(2000000, MSBFIRST, SPI_MODE3);
uint8_t tx_buffer[4];

void setup() {
  pinMode(cs_pin, OUTPUT);
  SPI.begin();
}

void loop() {
  tx_buffer[0] = 0xDE;
  tx_buffer[1] = 0xAD;
  tx_buffer[2] = 0xBE;
  tx_buffer[3] = 0xEF;

  SPI.beginTransaction(spi_settings);
  digitalWrite(cs_pin, LOW);
  SPI.transfer(tx_buffer, 4);
  digitalWrite(cs_pin, HIGH);
  SPI.endTransaction();
}

SCLK - CH1 (Yellow)
CS - CH3 (Purple)
MOSI - CH4 (Blue)

Expected signal:

SPI is synchronous. That means that within certain constraints the timing and the width of any part of the signal is irrelevant.

What makes you think that it's bad to have a slight variance in the timing, or that the "pause after CS goes LOW!" is "too low"?

If you think it's from the timing diagrams, those times are minimum times (generally) and all things happen at either the rising or falling edge of the clock (depending on the SPI mode).