Interrupt routine for button somehow respondng to room lamp turning off and on I have a sketch that has been running fine on an Uno 24x7 for a few months now.  The part of interest is an interrupt routine associated with a momentary contact switch [on pin 2].  When pressed, the interrupt routine handles debouncing and simply toggles a boolean variable.  The main routine checks status, takes action, warbles a buzzer, and does a Serial.print of the event.

Today, I moved the unit to the other side of the room and plugged it into a different PC via USB. Whilst it was running, I happened to turn on a nearby fluorescent light [not connected to anything but a 120v outlet].

The Uno buzzer went off, and appropriate msgs were written to the serial connection.  I flipped the light back on, and got the same kind of results.  I repeated this numerous times and got the same.  I could flip the light or push the button attached to the Uno, and the results were indistinguishable.

I unplugged the USB cable and used the power jack instead.  I got the same results, sans the print msgs to the serial connection.

The board itself has only a DS3231, an 8x8 LED matrix, a button, two LEDs & resistors, and a buzzer.

What is happening?  How can I resolve the problem?  [If another person had posted this, I would be disinclined to believe it, but surely someone out there understands the situation.]

I can readily supply a minimal code set and a Fritzing if it would help, though I suspect it would not.

Yours is a problem of EMI (electromagnetic interference). The ballast from the fluorescent light may interfere via two mechanisms:

Conducted EMI through the power lines (unlikely). In order to rule out this condition, power your Uno through a battery or a battery-powered device (a laptop disconnected from mains). If EMI effects disappear, then you have a problem of conducted EMI and you must use some kind of power-line filter. If it doesn't disappear, then it's a problem of radiated EMI (continue reading).
Radiated EMI (most likely). There are some things you can do to mitigate its effects:

Use wires as short as possible.
Twist wire pairs whenever possible.
Avoid operating conditions that leave inputs unterminated (be sure they're always either pulled up or low). This can easily happen when switchs are used and they leave an input in a high-impedance (disconnected) state.
Increase the debouncing time or use a more robust, glitch-tolerant debouncing routine.
Consider polling the input instead of using an interrupt. However, doing this will be of little use if you don't improve your debouncing routine.
Consider adding hardware debouncing.

Regarding the last three points, I recommend you to read this this. You'll have a better grasp about the art of debouncing inputs.

SPOILER: One thing you can do to make your debouncing routine far more robust is to wait for N consecutive readings with the same value (to happen during a given time T = N x Interval) before considering it good, instead of just waiting for a second reading after a constant time T.


Serial Monitor stops working when using PinMode I'm having a lot of trouble with my recent Arduino sketch. I need to reset an IC by setting a pin high then low. I also am using the serial monitor for some testing but as soon as I try and do a Serial.print, nothing appears. My Arduino is also on a custom PCB, where D7 is connected to the IC's (MAX3421) reset pin, and also to the Arduino's reset pin.
To try and make my issue clearer, ill post some code and the serial monitor output below:
void setup()
{
  Serial.begin(9600);

  pinMode(7, OUTPUT);
}

void loop()
{
  Serial.println("TEST");
}

[nothing in serial monitor]

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

  //pinMode(7, OUTPUT);
}

void loop()
{
  Serial.println("TEST");
}

[lots of TESTs]
Any help is appreciated,
Thomas

My issue was that pin 7 was connected to the reset pin on the Arduino, meaning every time it was set to output, the Arduino was reset.
You can see this here:
void setup()
{
  Serial.begin(9600);

  Serial.println("a");

  delay(100);

  pinMode(7, OUTPUT);
}

void loop()
{
  Serial.println("test");
}

which outputs a stream of a's separated by 100ms (plus a bit)


how to use arduino to detect an 8Mhz ultrasonic pulse using piezo disc as receiver? i need a code to detect an 8MHz ultrasonic pulse and show its properties eg wave pattern and amplitude on serial plotter( like an oscilloscope)

In a word: no.

Let's crunch some numbers...  You want detail like an oscilloscope.  Okay...

My scope is 50MHz bandwidth and runs at 1 giga samples per second.

Drop that down to 8MHz with the same kind of resolution, and you get (1,000,000,000 * (8/50)) = 160,000,000 samples per second.

That's 10 times more samples per second that the clock speed of the Arduino, and it takes at least 1664 clock cycles to take one sample.

So, no.  You need a board with an ADC which can run in the hundreds of millions of samples per second. The Arduino can only run at just under 10 thousand samples per second.

A slight discrepancy.

Even the Arduino Due can only get as good as 1Msps. I have seen MCUs with 15Msps theoretical maximum, but for the kind of output you want you would need considerably more.

So no, there won't be a cheap development "Arduino-like" board around that will do what you want. There may be an expensive one with a very fast CPU, DSP, ultra-high-speed ADC, etc, but you won't be programming it with Arduino, and you most likely won't be able to afford it to just play with.


I use Bluetooth to control LED,but LED can not turn off I use android to send the data to Arduino. when i send 0x02, LED turn on, and the breathing LED code are work. But when i send 0x03, it can not turn off the LED. i use UNO R3 the bluetooth is HC06

char data;
void setup()
{
  Serial.begin(9600);
  pinMode(9, OUTPUT);
}

void loop()
{

  if (Serial.available())
  {
    data = Serial.read();

  switch(data){

    case 0x02:

      for (int a = 0 ; a < 255; a=a-1){
        analogWrite(9, a);
        delay(10);
      }
      for (int a = 255; a>0; a=a-1){
        analogWrite(9, a);
        delay(10);
      }

      break;
    case 0x03 :
      digitalWrite(9, LOW);
      break;
    default:
      break;
    }
  }
}

this may be because of using digitalWrite in 0x03. Try using analogWrite(9, 0); instead.


Convert library from using bitbanging to hardware SPI I'm using a MCP3008 8ch 10bit ADC to expand the Analog Inputs for the project I'm working on. The only library I can find for it is here the library is ported from Adafruit's Raspberry Pi library here. From what I can tell the library uses bitbanging as opposed to hardware SPI in order to communicate. I would like to use hardware SPI, but don't have the skills to write a library to communicate with it myself. Are there any resources for how to write a library like that, or anything I can read about on how to convert a library from bitbanging to hardware SPI?

The standard AVR library has SPI handling. See, for example: http://www.gammon.com.au/spi

You don't have to write a library if you don't want, just communicate directly using SPI.

The datasheet for the MCP3008 has some tips for using an 8-bit SPI system to communicate with the device. In particular this chart:

You can see from that, that you will need 3 x SPI.transfer. I don't have one here to test with, but the code would look like this:

digitalWrite (SS, LOW);  // select device
int result;
SPI.transfer (0x01);  // start bit
result = SPI.transfer (0b10000000);  // single, ch0
result = (result & 0b11) << 8;  // move to high-order byte
result |= SPI.transfer (0);   // lower order byte
digitalWrite (SS, HIGH);  // deselect

Untested, but this should be roughly it.


esp8266 not responding to the AT commands I am integrating Arduino Uno with the WiFi module ESP8266.  I have already made the connections between the ESP8266 and the Arduino Uno which are :

txd uno -> rxd esp8266
rxd uno -> txd esp8266
gnd uno -> gnd esp8266

The VCC and chid pind of ESP8266 are connected to an external supply of voltage 3.3V and 160mA current. The code is getting uploaded onto the Arduino and the ESP8266 is also getting powered on.But i am facing a problem while i send the AT commands on the serial monitor. It is not responding even though the red led is on constantly and when i press enter after sending the command , the blue led blinks for a few seconds.
Do i have to update the firmware of the ESP8266?

I had same problem. It helped to connect GNDs of both power supplies namely the one powering the arduino and the 3.3V one powering the ESP8266.


RC servo misbehave using arduino and MPU6050 I am a beginner.. I am trying to control RC servo using Arduino based of data from MPU6050.
I am using library I2Cdev to communicate with gyro and to get yaw, pitch and roll. I am using example script which I have modified to control servo based on received data.

mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

Serial.print("ypr\t");
Serial.print(ypr[0] * 180 / M_PI);
Serial.print("\t");
Serial.print(ypr[1] * 180 / M_PI);
Serial.print("\t");
Serial.println(ypr[2] * 180 / M_PI);

pitch_angle = (ypr[1] * 180 / M_PI) + 90;
roll_angle = (ypr[2] * 180 / M_PI) + 90;

Serial.print(pitch_angle);
Serial.print("\t");
Serial.println(roll_angle);

pitchServo.write((int)(pitch_angle));
rollServo.write((int)(roll_angle));

Without servo being connected everything works well.
But after I plug in servo after few second being still (it seems to even follow movement of gyro) it starts to shake and then probably whole Arduino stops working (serial transmission of data stops) and Arduino has to be restarted.

100 95
ypr 12.21   10.51   5.49
100 95
ypr 12.23   10.31   5.48
100 95
ypr 12.25   10.15   5.45
100 95
ypr 12.27   10.02   5.45
100 95
ypr -13.31  30.81   55.76
120 145
ypr 20.53   -21.36  -52.59
68  37
ypr 64.96   35.38   10.25
125 100

I tried to plug two 100 nF capacitors across power and ground of the servo and I tried to connect servo in to different power source than Arduino.

EDIT:
Servo is not fixed with MPU6050 so there shouldn't be any resonance at least on the mechanical base.
Wiring is very simple:

Any idea? Thanks

At the end two pull-up resistors and one capacitor solved the problem.

I followed instruction here:

http://www.instructables.com/id/Brushless-Gimbal-with-Arduino/step3/Using-the-Accelerometer-and-Gyro/

Now it works well.. Thank you all.


Optimizing an Arduino code I am working on project and using Arduino Pro Mini (Atmega328p running on 2xAA) to measure the time to charge a capacitor (when the volt level is high). This is the code I used while testing:

int counter = 0;

// Charge the capacitor
digitalWrite(8,HIGH);

while (digitalRead(7) == LOW) {
    counter = counter +1;
    if (counter > 250) {
        break; // CHARGING FAILED!
    }
}

The code was working fine when the board was running at 16MHz since the loop was fast enough to give good result. ( counter =~ 28 when the test cap is charged).

However, the intention is to run the system on a battery with clock of 1MHz (to reduce power consumption) and when tested at that speed the counter only reaches 2~3 because the loop it too slow now that the cap will charge in about two to three cycles.

So I did two changes which are using byte instead of int for the counter, and reading the value of the pin directly from the PIND register:

byte counter = 0;

// Charge the capacitor
digitalWrite(8,HIGH);

while ((PIND & (1<<PD7)) == 0) {
    counter = counter +1;
    if (counter > 250) {
        break; // CHARGING FAILED!
    }
}

Both of these changes increased the speed and now counter reads ~20 which is much better and almost close to the 16MHz.

Is there any further optimizations?

Can I use one of the general registers instead of the counter, if yes then how? and will that improve the speed?

Is there a more clever and faster way to do this loop?

Update:

I am going to follow the suggested answer and use the analog comparator, but I also wanted to add to my finding which might help others with general optimization.

Instead of incrementing the counter and comparing if it is larger than some value, it is faster to decrements and compare if it is equal to zero. The counter improved to ~23.

Get rid of the loop altogether. Instead of twiddling and checking bits manually, use timer 1 to trigger the output and capture the input.

If you perform the output on pin 10 and the input on pin 8 then you can use timer 1's output compare to send the pulse out and its input capture to detect when the capacitor has charged.

Untested:

#include <avr/interrupt.h>

void setup(void)
{
  cli();
  DDRB |= _BV(PB2); // Configure OC1B as output
  TCCR1B &= ~(_BV(CS12) | _BV(CS11) | _BV(CS10)); // Stop timer 1
  TCNT1 = 0; // Initialize timer count
  OCR1A = 0xffff; // Reset the timer at this count
  OCR1B = 0xf000; // Upper limit of the timed value, plenty of time before timer reset
  ICR1 = 0xff00; // Set to an invalid initial value
  TCCR1A = _BV(COM1B1); // Trigger output at 0, clear at upper limit
  TCCR1B = _BV(ICES1); // Capture on leading edge
  TCCR1B |= _BV(WGM13) | _BV(WGM12); // High bits for 16-bit fast PWM
  TCCR1A |= _BV(WGM11) | _BV(WGM10); // Low bits for 16-bit fast PWM
  TIMSK = _BV(ICIE1) | _BV(OCIE1B); // Enable input capture and limit interrupts
  sei();
  TCCR1B |= _BV(CS10); // Start the timer at its highest clock speed
}

ISR(TIMER1_CAPT_vect)
{
  TIMSK &= ~(_BV(ICIE1) | _BV(OCIE1B)); // Disable input and limit interrupts
  TCCR1B &= ~(_BV(CS12) | _BV(CS11) | _BV(CS10)); // Stop the timer
  PORTB &= ~_BV(PB2); // Kill the charging output
  // Check ICR1 for the captured value
}

ISR(TIMER1_COMPB_vect)
{
  if (ICR1 == 0xff00)
  {
    // WELL CRAP, charging is taking too long
    // Maybe try with a slower clock?
  }
}

void loop()
{
  // Do other stuff
}


10k ohm Potentiometer vs 10k ohm Resistor on LCD Display I'm trying to use a LCD Display with my Arduino, but I don't have a potentiometer and all of the guides I find always require one, usually a 10k ohm potentiometer.

The point is that I'm not very good at this stuff, but I understand that the potentiometer is actually a resistor that can vary, am I correct? In that case, if I use a simple 10k resistor I would have the same result as if I was using that potentiometer at the higher resistance (10k).

Would it be correct to use the resistor instead of the potentiometer? Then I would have to plug the positive on one side of the resistor and both the negative and output to the LCD on the other side of the resistor?

No, it would not be correct to use a single resistor to replace a potentiometer.

On an LCD the potentiometer is used to adjust the bias level of the LCD - that is the contrast.  You need to use it to set a voltage between Vcc and Vee, which you feed into Vo.  That is, a voltage somewhere between +5V and -5V.

You can't do that with one resistor.

You can, however, do it with two resistors.  Some experimentation will provide the right values to use.  Pick a pair of resistors which add up to around 10K (the exact value doesn't matter that much) and join them together end to end.  The two ends are the equivalent to the ends of the track of the potentiometer, and the join in the middle is the wiper.

To change the "value" of the potentiometer you then need to change the value of both resistors.  If you reduce one resistor you need to increase the other so that they still add up to around the same value.  What you are working with here is not the actual values of the resistors, but the ratio of the values of the two resistors.


How do I make my Arduino do a specific action when the computer is locked/unlocked? I have a windows computer connected to my Arduino Uno. I work in a area with a bunch of cubicles and we leave our desk fairly regularly to go and troubleshoot other computers (I'm a service desk technician).
When we leave we are instructed to raise and lower a small flag so management can see whether or not we are sitting at our desk. I've attached my arduino to a servo motor with the following code.

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
#define servoPin 3 //~
#define pushButtonPin 2

int angle =0;    // initial angle  for servo
int angleStep =20;
const int minAngle = 0;
const int maxAngle = 90;

int buttonPushed =0;

void setup() {
  // Servo button demo by Robojax.com
  Serial.begin(9600);          //  setup serial
  myservo.attach(servoPin);  // attaches the servo on pin 3 to the servo object
  pinMode(pushButtonPin,INPUT_PULLUP);
   Serial.println("Nathan's Status flag");
}

void loop() {
  if(digitalRead(pushButtonPin) == LOW){
    buttonPushed = 1;
  }
   if( buttonPushed ){
  // change the angle for next time through the loop:
  angle = angle + angleStep;

    // reverse the direction of the moving at the ends of the angle:
    if (angle <= minAngle || angle >= maxAngle) {
      angleStep = -angleStep;
       buttonPushed = 0;
    }
    myservo.write(angle); // move the servo to desired angle
      Serial.print("Moved to: ");
      Serial.print(angle);   // print the angle
      Serial.println(" degree");
  delay(100); // waits for the servo to get there
   }
}

We also have a policy that we need to keep our computers locked for obvious reasons. I learned my lesson with that early on. I would like to edit my code so that when I lock my computer the flag goes down, then when my computer is unlocked it goes back up. That way as long as I remember to keep my computer locked when I'm away I don't have to worry about the flag. Here is my breadboard/arduino layout.

I also have processing on my computer and am planning on using that. (https://processing.org/)
Any help is greatly appreciated.

Read a value through serial (what exactly is entirely up to you) to do the same job the button does now.
Use Serial.read() to get that data, and Serial.available() to know if there is any data to read.
How you generate that value on the PC to send through serial we cannot help you with, as that is outside the scope of this site.


What is this extender? I recently got an Arduino starter kit from a friend that he wasn't using and this came with it but, i can't find anything about it, cause i don't know how to search for it.
Anyone can enlighten me what it is?

Looks similar to:
"8 Channel 5V/3.3V IIC UART SPI TTL Logic Level Converter"

Image above was screen capped from: https://www.aliexpress.com/item/32977711795.html


NRF24L01 integrated antenna exposed out of the box I'm going to try my hand at making a few sensors that are to report status to a central server. To make them wireless, I'm going with nRF24L01 modules. I intend to enclose the sensors (Arduino Mini Pro + nRF24L01 + battery pack + a couple of other small components) in a simple PVC box.

A couple of the sensors would be about 10 meters away from the server, which, as far as specifications go, is about the maximum range of the radio modules. Especially the ones with the integrated antenna that I'm using. I thought that maybe I could squeeze some radio performance by exposing the antenna, so that the radio signal isn't attenuated by the PVC case. I could carve a small opening in the lid and have the nRF24L01 stick out, so that the electronics would be protected inside but the antenna strip would enjoy open air.

I would like some thoughts on this idea. I'm especially trying to understand if I just had the most novel idea ever, since I can't seem to find anything about it on the net. Has anyone ever tried this in real life? Does it make sense? Is it worth the trouble?  I'm not looking for a theoretical analysis (I get that fine), only for actual experience. Thank you.

In general no, this would make little or no difference. PVC has very little effect on RF signals.

After all, the antenna on your typical WiFi router is inside a PVC tube and it doesn't suffer from it.

Instead you would do better constructing a dipole antenna from a couple of pieces of carefully measured wire.

For instance this instructable tells you how.


Design Dilema -- What hardware? I'm trying to build a smart thermostat for a particular application. I have the following design criteria and goals for the system:

Must be able to set up and monitor the device from either a mobile
phone or local network device.
No go on Ethernet or other hardwired connection, except for initial setup.  This must be a wireless solution. I'm presuming WiFi is best.
Needs a clock, an on time and an off time setting.
The system does a system time verification check once daily.
Needs a temperature input.
Needs to run an existing heater system (24v) thru a relay.
120v AC power (battery backup not required.)
Needs to be "hidden" in existing wall as much as possible.  (i.e. small & compact)  My intent is to hide the unit behind a double wide electrical duplex dead panel. (i.e. 4" x 4" nominal access thru drywall)

Here's a visual of my design intent package:

As I review a number of different hardware controller devices, I can see some issues.  I am very familiar with the Intel Edison, and I know exactly how to do this project there, including using the controller as a stand alone web host. (The Edison uses Yocto Linux to create a node.js server using http module.)  I was hoping to save a few $$ on hardware using an alternative controller but not sure that will work.  I've been wading thru the code for both the Photon and generic Arduino devices, and I'm getting the impression that I may need a custom server / api tool for a web page interface.  Its not clear that those hardware choices will support an interactive web page, particularly for easy user data update via browser Submit button.  That's not a big problem, I'm a freelance software developer, handy in C/C++/Java, PHP and JavaScript. And as for the Raspberry Pi, I have no experience but the pricing on some of their boards is below $15.

Here are my questions:

Has anybody used an Arduino board to host an interactive web page, including user input via Submit / Form ?  (Can I declare a local network static IP address for an Arduino?)
Has anybody used an Particle Photon board to host an interactive web page, including user input via Submit / Form? (It looks like declaring a local network static IP address on a Photon is anything but easy...)
Has anybody written an API Restful server for their Arduino, with both get and put functionality?  (I'm thinking PHP, or node.js makes the most sense for me.)  I know if I have to use Dynamic IP addressing to the controller, that I can always make an API system work for the system.
Other comments?

Has anybody used an Arduino board to host an interactive web page, including user input via Submit / Form ?

I have a Tiny Web Server for the Arduino. It is designed to be light-weight on RAM. It supports GET/POST/Cookies for interacting with web forms.

Example code and more information on the linked page above.

  (Can I declare a local network static IP address for an Arduino?)

Yes.

  Other comments?

You could use NRF24L01 modules for short-range communication of wireless information. I have example code and schematics. My tests seemed to indicate 20m range was achievable.


Controlling 3 stepper motors simultaneously I have three stepper motors connected to the drv8825 drivers to an arduino uno.

I am using the example code below (from here), which works fine for moving multiple stepper motors at the same time BUT they all move for the same number of steps and in the same direction. I would like to tweak the code so that all of them move at the same time but each one for a different number of steps and in different directions. The motor with the least steps would probably have to wait for the motor with the most steps to finish its movement before going again.

int dirPin = 8;
int stepperPin = 7;
int bdirPin = 6;
int bstepperPin = 5;

void setup() {
 pinMode(dirPin, OUTPUT);
 pinMode(stepperPin, OUTPUT);
 pinMode(bdirPin, OUTPUT);
 pinMode(bstepperPin, OUTPUT);
}
 void step(boolean dir,int steps){
 digitalWrite(dirPin,dir);
 digitalWrite(bdirPin,dir);
 delay(50);
 for(int i=0;i<steps;i++){
 digitalWrite(stepperPin, HIGH);
 digitalWrite(bstepperPin, HIGH);
 delayMicroseconds(800);
 digitalWrite(stepperPin, LOW);
 digitalWrite(bstepperPin, LOW);
 delayMicroseconds(800);
 }
}
void loop(){
 step(true,1600);
 delay(500);
 step(false,1600*5);
 delay(500);
}

Thank you in advance for your help!

You need a struct for each stepper with a timestamp, a position and rate of change and a loop that updates the postion based on rate which is the change in position over some time:

struct stepper {
  unsigned long timestamp;
  int position;
  int rate;
};

// init steppers array

while (keepGoing()) {
  unsigned long now = millis();
  int si;

  delay(10);

  for (si = 0; si < 3; si++) {
    struct stepper *stepper = &steppers[si];

    if (steppers[si].timestamp > now) {
       steppers[si].position += steppers[si].rate;
       steppers[si].timestamp = now + 100;
    }
  }

This is a back-of-a-napkin sketch of course. It is only supposed to illustrate how you can update any number of things concurrently.

The important thing is that you only call delay once. And presumably it would be only a very short delay compared to the unit of time for the rate. In the above example it would adjust the stepper position every 100ms. You would need to experiment with the timing to find a good behavior given the speed of the stepper, speed of the code and maximum permitted rate.

Beware that there is a lot to think about beyond this. For example, you should initialize the timstamps with different timestamps so that the motors are not all running at the same instant and thus try to minimize the total power consumed by the motors at any particular time.

Note that I have never played around with stepper motors but this type of loop is a common programming idiom for handling things concurrently.


Do I have to use an external power supply when connecting an ultrasonic sensor to Arduino? This might be a very stupid question but please bear with me. So I am using an HC-SR04 Ultrasonic sensor model (5 V) and I want to connect it to Arduino Uno. Do I have to use an external power supply for the ultrasonic sensor (just like with the motors) in order to connect it to the Arduino? Or can I just use the 5 V pin?

From the question I assume you power your Arduino via USB in which case you don't need an external supply. The HC-SR04 draws 15 mA with is far below the specifications for USB. I did this myself some time ago:


How to free up Flash space by removing the bootloader on UNO? In order to fit maximum user program into the chip, how to free up Flash space (0.5 kilo bytes for UNO, 2 KB pro Mini, 8KB for ATMega2560) by removing the bootloader on Atmega328 (UNO, Pro Mini, or similar)?

What software development tools needed (like Atmel AVR Studio software or similar)?

What hardware flash writing / debug tools needed (like JTAG hardware programmer/debugger)?

How is the procedure? Where can I get more information.

Many thanks in advance.

edit: Update boot loader size for different boards

You'll need to use an ISP programmer with avrdude. Perform a chip erase and then unprogram the BOOTRST fuse in the high fuse byte.


Unable to obtain pulse train at 32Hz with 20us pulse width with Uno I tried to obtain 32Hz pulse train(between 30Hz and 35Hz is also fine) with around 20us pulse width with Arduino Uno but couldn't succeed. The problem is:

If I do the following:

void setup() {

    TCCR1B = TCCR1B & B11111000 | B00000101;

    pinMode(pwmPin9, OUTPUT); // sets the pin as output

}

void loop() {

analogWrite(pwmPin9, 1)

}

I can set the freq. roughly at 30Hz but analogWrite(pwmPin9, 1) will give minimum 100us cannot go down to 20us.

digitalWrite method with delay on the other hand doesn't work to obtain frequencies below about 60Hz.

How can I obtain a pulse train output with between 30Hz to 35Hz and with around 20us pulse width?

For this kind of problems, the first thing to do is convert the two
relevant times (the signal period and the duration of the HIGH state)
into a number of CPU cycles. With a 16 MHz clock that gives:

HIGH time: 20 µs =    320 CPU cycles
period: 31.25 ms = 500000 cycles (±7%)

Then divide those numbers by the available prescaler values, to get the
corresponding number of prescaled clock cycles:

prescaler       1      8    64     256      ...
HIGH time     320     40     5       1.25   ...
period     500000  62500  7812.5  1953.125  ...

Ideally, you want a prescaler that gives you integer numbers, in order
to avoid rounding errors. And since you are using a 16-bit timer, you
want these numbers to be no larger than 216. Or twice that if
you use a phase-correct PWM mode, but I prefer to avoid that
complication if possible.

From the table above, it appears that a prescaler of 8 is ideal. 64
would be practically as good, with a frequency error of only
64 ppm, which is less than the frequency tolerance of the ceramic
resonator clocking your Uno.

Then you use either OCR1A or OCR1B to set the high time, depending
on whether you are outputting to pin OC1A (digital 9) or OC1B (digital
10). An you use either OCR1A or ICR1 to set the period. Since you
are outputting on pin 9, the OCR1A register will be used to set the
high time, thus you have to use ICR1 to set the period. Then you
search the table of modes in the datasheet and find the one relevant to
this mode of operation is mode 14: fast PWM with the TOP value
defined by ICR1. This gives the following configuration:

void configure_timer_1()
{
    DDRB  |= _BV(PB1);    // set pin 9 = PB1 = OC1A as output
    TCCR1A = 0;           // reset timer
    TCCR1B = 0;           // ditto
    OCR1A  = 40 - 1;      // HIGH for 40 * 8 CPU cycles
    ICR1   = 62500 - 1;   // period = 62500 * 8 CPU cycles
    TCCR1A = _BV(COM1A1)  // non inverting PWM on pin OC1A
           | _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS11);   // clock at F_CPU/8
}

Note that OCR1A and OCR1B have to be set to desired number of cycles
minus one.


Cannot find crtatmega328p I have just installed the arduino IDE on my gentoo laptop. I then installed the toolchain with the following command:

crossdev -s4 avr

This does a stage 4 install of the toolchain, with all its dependecies etc.

I am following a tutorial, with my arduino uno, which I am assuming is using the Amtel ATmega328 chipset. This tutorial is simply going to turn an led on and off.

I click the verify button and I get the following errors:

/usr/libexec/gcc/avr/ld: cannot find crtatmega328p.o: No such file or directory

/usr/libexec/gcc/avr/ld: cannot find -latmega328p

collect2: error: ld returned 1 exit status

I downloaded the source files "avr-libc" compiled them and noticed inside the directory

/avr-libc-1.8.1/avr/lib/avr5/atmega328p

That the compiled module is named crtm328p.o which is available on my pc under the directory:

/usr/avr/lib/

I dont understand what is wrong and why this is not working. The only posts relating to missing files are over 5 years old and those solutions are not working.

I do not use Gentoo, but I can tell you how things work on Ubuntu 14.04,
which also installs Arduino 1.0.5. I assume Gentoo should not be that
different... The dependency tree is like this:

The package named "arduino", version 1.0.5, contains the IDE. It
depends on Java and on arduino-core.
arduino-core, version 1.0.5 also, has the Arduino core libraries. It
depends on gcc-avr, avrdude and avr-libc.
gcc-avr comes as version 4.8, avr-libc is version 1.8.0.

When you compile a program for an Uno, on the link stage avr-g++ gets
called, and it is asked to link your object files with libcore.a (the
Arduino core) and -lm (the math library). avr-g++ in turn calls the
linker (collect2) and asks it to link together
/usr/lib/avr/lib/avr5/crtm328p.o (the C runtime), your object files,
libcore.a, -lgcc (the GCC support libraries), -lm and -lc (avr-libc).
Notice that there is no crtatmega328p.o, it's called crtm328p.o instead.
And there is no -latmega328p.

For diagnosing your problem, you can set an IDE preference so that it
shows you the exact command lines it runs for compiling your program.
You can then copy and paste the last command (link stage) on a terminal.
If you add the -v option (meaning “verbose”), you will see what gcc is
asking the linker to put together.

You may be able to fix your problem with a simple symlink from
crtm328p.o to crtm328p.o. If you are using vanilla Gentoo packages, you
should then file a bug to the packager. On Ubuntu, you type
sudo apt-get install arduino and it just works.


Using serial.available to return number of bytes My code:

char data;
int numOfBytes;
void setup() {
    Serial.begin(9600);
}
void loop()
{
    if (Serial.available() > 0)
    {
        int numOfBytes = Serial.available();
        Serial.print("numOfBytes: ");
        Serial.println(numOfBytes);

        data=Serial.read();
        Serial.print("data: ");
        Serial.print(data);
        Serial.print("\n-----------\n");

        delay(500);
    }
}

I expected that this code returns 5 and then 4,3,2,1.
But it returned: 1,4,3,2,1

Why?

This is because at the first execution only one byte was received. The Serial interface does not send the data in one big packet of 5 bytes, only because you typed five bytes and started the transmission of all with one press in enter. It is sending the bytes one by one, in other words serial (hence the name). The exact transmission time is dependend on many factors (especially, when other technologies are involved, like the USB interface, when you are transmitting over the Arduinos USB to serial converter).

In this case the first byte is sent, followed by a short break, then the other bytes. The Arduino is fast enough in checking the Serial interface to sense this at 9600 baud.


Issue with Serial PINs (RX/TX) on Arduino I have an issue with an Arduino Nano.

I want to communicate with it through the Serial-Port. Meaning I want to send and receive Serial commands. With USB and the "Serial Monitor" this works nice.
Now I have connected the COM-Port of the PC with Adruinos Digital Pins 0 and 1 (RX and TX) and a GND PIN. (3 Cables total).

Here is a minimal example of my Code:

void setup() {
  Serial.begin(9600,SERIAL_8N1);
  Serial.println("Start");
}

void loop() {
  Serial.println("Hello World");

  delay( 1000 );
}

The Serial Monitor says:

Start
Hello World
Hello World
Hello World
Hello World
...

Putty however says:

▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒::
                                                     ▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*▒▒    ▒R▒▒▒t▒*▒▒▒R▒▒▒t▒*

Putty is connected with
- BaudRate: 9600
- Data Bits:
- Stop Bits: 1
- Parity: None
- Flow Control: None

What is wrong here?

Update:
The PC has a 9-pin D socket (Image)
This is connected to a RS232 to RJ45 connector (image)
From the RJ45-Cable I used the Brown, Blue, and White/Green Cable to connect with the Arduino

RS232 is not TTL. You need a level converter. For more details see https://www.sparkfun.com/tutorials/215.


Change the backlight of 2x16 LCD Today I ordered a 2x16 character LCD with white characters on black background.

Now I am wondering if I can change the backlight LED, which I guess is white for the characters, with a RGB LED to change the character color.

Did anyone do this before?
Is it even possible that way?

I've seen RGB negative LCDs from Adafruit and Sparkfun.

The product you linked looks like a fairly standard LCD module, so it's probably very difficult to swap the backlight LED. Like most electronics, they're not designed to be modified by hand. It would likely need some precision re-soldering.

When you see LCDs with other types/colours of backlight, it's usually because they were originally manufactured that way.


Verify a code for Traffic Signal void setup() {
  pinMode(13, OUTPUT);  // Red
  pinMode(14, OUTPUT);  // Yellow
  pinMode(15, OUTPUT);  // Green
}

void loop() {
  digitalWrite(13, HIGH);
  digitalWrite(14, LOW);
  digitalWrite(15, LOW);  // Stop
  delay(20000);           // Wait 20 seconds
  digitalWrite(13, HIGH);
  digitalWrite(14, HIGH);
  digitalWrite(15, LOW);  // Listen
  delay(20000);           // Wait 20 seconds
  digitalWrite(13, LOW);
  digitalWrite(14, LOW);
  digitalWrite(15, HIGH);  // Go
  delay(20000);            // Wait 20 seconds
}

How good is this code and is there any error ?

There is nothing wrong with your code. But it could use some cleaning to make it efficient.

The code at the moment will be 'deaf' to any user inputs for twenty seconds between light changes.

This can be fixed by using a timer interrupt and changing the lights every 20 seconds and listen for other inputs or do other things. You can use the arduino timer library, this is well documented and you should be able to find examples of its use. Basically you would monitor a variable until it reaches a point and then trigger the lights.

The other option would be to use the millis() and every 20 seconds change a light, but do stuff between those 20s. This can be done like this:

unsigned long previousMillis;  //hold the previous time
unsigned long currentMillis;   // hold the current time

long threshold = 20000;
int count = 0;

int pins[] = {13, 14, 15};

//setup code stuff

//put the following at the top of loop()

currentMillis = millis();

if(currentMillis - previousMillis > threshold){

    previousMillis = currentMillis;

    for(int i = 0; i < 3; i++){
    digitalWrite(pins[i], LOW);  //turn off all

    }

    if(count > 2) count = 0;

    digitalWrite(pins[count], HIGH);

    count++;
}


My Servo Won't Sweep Smoothly So I've tried this a few times and I always get the same issue. When I try to run the sweep example the servo goes round 180 degrees but only in steps. Anyone know a way to fix this?

The servo I'm using is a Tower Pro Micro Servo 9G SG90

// Sweep
// by BARRAGAN <http://barraganstudio.com>
// This example code is in the public domain.

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // a maximum of eight servo objects can be created

int pos = 0;    // variable to store the servo position

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

Video: http://vidd.me/A40

In electronics, as usual in situations where a cricuit is misbehaving and we don't understand why, a solution that generally works is to add a decoupling cap between +5V and GND.

In your case, I would put at least 220uF; that would ensure two things:

the voltage used to control the servo never drops
the voltage brought to Arduino by the USB does not drop either (which would have very bad impact on the Arduino, probably resetting it)

Electrolytic caps are a must-have for every electronics hobbyist (and professional as well, of course).

You can read more about decoupling capacitors on Wikipedia.

Edit:

According to @gwideman comment, it seems that using a decoupling capacitance above 10uF in a USB 2.0 device would violate USB specs and may damage the USB host controller on the computer.

I was not aware of this limitation but I have already used decoupling capacitance up to 100uF in my circuits and never got any issue with my USB computer port.

It might be due to extra electronics on the Arduino board that would "isolate" USB power from Arduino +5V anf d GND pins, I don't know (that should probably be the topic of a specific question); or maybe I have just been lucky all this time...


Install Arduino IDE in Raspberry Pi 3 model B I am trying to install Arduino IDE in my Raspberry Pi model 3 but it is unable to locate file path.

I use the following steps

sudo apt-get update && sudo apt-get install arduino

and in result I found this

pi@raspberrypi:~ $ sudo apt-get update && sudo apt-get install arduino
Hit:1 http://archive.raspberrypi.org/debian stretch InRelease
Ign:2 http://repository.pi4j.com wheezy InRelease
Hit:3 http://repository.pi4j.com wheezy Release
Reading package lists... Done
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package arduino

I am searching for a solution but not able to understand what's the problem here.

Any ideas to make it work will be helpful.

Visit https://www.arduino.cc/en/Main/Software in your browser, and click the Linux ARM link under ‘Download the IDE’.

cd Downloads/
tar -xf arduino-1.8.3-linuxarm.tar.xz

Extract the file to your /opt directory, then open a Terminal and run the install.sh script to install.

sudo mv arduino-1.8.3 /opt
sudo /opt/arduino-1.8.3/install.sh

You will find Arduino IDE under Menu > Programming. Open the app to start programming your Arduino board.

Hope this helps.


Can a pin be Neutral, not high or low? I'm trying to figure out a way to controll a DFplayer mini mp3 player with ADkeys.
Because I only have two or three files to play at a fixed volume I find it easier to just use the ADkeys. https://wiki.dfrobot.com/DFPlayer_Mini_SKU_DFR0299#target_4

Lets say I want to use Segment 1 - Segment 3 (MP3 file 1 - MP3 file 3). I would then connect a resistor (or none in Segment 1) in between and to three pins on the Arduino.
But how can I make the pin neutral, so that it does not trigger everything at once?
As far as I can read the pins are grounded in Arduino if not "high".

What you are talking about in this instance is "Open Drain".  Normally, as you rightly note, with outputs you have either HIGH or LOW, which effectively connects the output pin to +5V or GND respectively.

Instead you are asking for Open Drain.  In this arrangement a pin is either "active", in which case it connects it to GND, or "inactive", in which case it is disconnected from (almost) anything.

Most 8-bit Arduino boards don't have Open Drain capability on their IO pins (some more advanced 32-bit boards do, though), but it is easy enough to emulate it in software.

You can emulate it using "Tri-State" logic.  That is logic where, as well as HIGH and LOW you have "High Impedance", or "HI-Z".  HI-Z is pretty much the same as "inactive" Open Drain. On the Arduino HI-Z is the same as INPUT.

So you can emulate it by:

To activate a pin set it to OUTPUT and LOW
To deactivate a pin set it to INPUT

For example, to "press" one of your buttons for 100ms you could:

pinMode(4, OUTPUT);
digitalWrite(4, LOW);
delay(100);
pinMode(4, INPUT);


Make Sure \n is the last character in serial string I have an Arduino that I've put between a computer and an RS485 device. The job of the Arduino now is just to transmit data but will eventually do data logging and have a small user interface as time goes by.

So far, this serial read code has worked for me to communicate to the Arduino from the computer:

 void serialEvent()
 {
  while(Serial.available())
  {
    // get new byte
    char inChar = (char)Serial.read();
    if (inChar == '\n')
    {
      stringComplete = true;
    }
    else
    {
      inputstring += inChar;
    }
  }
 }

The downside here is that I cannot send the '\n' char to my RS485 unit. Is there a way I can refine the code so I can send an arbitrary string of chars while still having a termination [thing] to turn on the stringComplete flag?

EDIT To clarify this the process by how my message string is being created:

Input: U16 Address, U16 Data, U8 Function Code
U16 Address -> U8 Address Split High, U8 Address Split Low
U16 Data -> U8 Data Split High, U8 Data Split Low

U8 Array of [U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]

U8 Array -> Message String

Output: Write Message String

Since you are using all 8 bits of the serial data for your data there is nothing "in band" that you can use for a delimiter.

Instead you will have to think outside the box somewhat and create some form of "out of band" data that can signal the end of a packte.

One option (probably the simplest) would be to include the concept of time into your protocol.  If you go more than X milliseconds (X is to be determined by you) without receiving a byte then you are at the end of your packet. This has the disadvantage that it slows down your maximum packet rate, since each packet has to have a suitable delay between them.

Another option may be to use a serial break character between packets. This is a special event where the UART output is held low for at least 10 symbol lengths, which results in an framing error (the STOP bit is wrong) and a flag being set. It would mean though that you have to implement all the UART code yourself since the Arduino's UART code doesn't support breaks.

A third option, which also would require you to write your own UART code, or alter the Arduino UART code, would be to operate the UART in 9-bit mode. You then have 0-511 instead of 0-255, so you can send your 8-bit data as per normal (with the 9th bit set to 0) and any control and protocol characters with the 9th bit set, so between 256 and 511.

Finally, you could halve your overall transmission speed by sending the data as ASCII-encoded HEX digits. That would be two characters (0-9,A-F) for each byte sent, leaving all the other characters (including \n) available for you to use as you wish.


Is there a way to play sounds from an Arduino without using a sound shield? I would like to play a wav file (spoken words) from my Arduino.  I do not want to add a sound shield.  Is there a way to play a sound through an output pin?  The quality does not have to be great.

I helped someone with a similar question. The results are in my github repo at https://github.com/linhartr22/count. This example uses the PWM library and includes a reference to the article I used to learn how to convert audio files to MP3 with proper settings for the PWM libary. It plays audio through an 8 ohm speaker or a piezo buzzer connected directly to the Arduino.


Alternative to delay function I am trying to make a workaround for the delay function. I am trying to use the function in the Analog Write Mega example, by replacing delay with the function i made. However, whenever i use my function instead of delay i get incorrect led behaviour.

Here is the link to the example:

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

Here is my code:

int currmillis = 0; //used in my function to find the current millis()
int prevmillis = 0; //used to hold previous value of currmillis
int boolval = 0;    //used to control whether to write the brightness value to the led or not
int time = 0;     //used in the delay function, difference between currmillis and prevmillis

int timeloop(int); //the function i wrote, it is at the bottom of the code

void setup() {
  Serial.begin(9600);
  for ( int i = 2; i <= 13; i++)
  {
        pinMode(i,OUTPUT);
  }
}//Setting the pins to output and allowing serial communication.

void loop (){

  for ( int thisPin = 2; thisPin <= 13; thisPin++ ) //to move from one led to the next
  {

    for ( int brightness = 0 ; brightness <= 255; brightness++) //change the brightness of the led
    {

      boolval = timeloop(2); //the delay function returns the time passed, if the time is greater than or equal to 2, the analogWrite will write the brightness to the led

      if (boolval >= 2){
            analogWrite(thisPin, brightness);
      }// if 2 ms pass, the led brightness will increase from 0 to 255 and then decrease in the following loop from 255 to 0, Once it reaches 0, the main loop moves to the next led.

    }

    for ( int brightness = 255 ; brightness >= 0 ; brightness--)
    {
      boolval = timeloop(2);

      if (boolval >= 2){
            analogWrite(thisPin, brightness);
      }
    }
          timeloop(100); // a delay of 100 ms using the function
  }
}

int timeloop (int interval){ // the delay function

  do{
    prevmillis = currmillis; //hold previous value
    currmillis = millis(); //find current value
    time = (currmillis-prevmillis);
  }while(time < interval);

  return time;
}

Thank you

// You don't need to return anything since it's just a delay
// also I changed the parameters to long ints because millis()
// returns a long int
void timeLoop (long int startMillis, long int interval){ // the delay function

    // this loops until 2 milliseconds has passed since the function began
    while(millis() - startMillis < interval){}
}

// Your call for a 2 millisecond delay would be
timeLoop(millis(), 2);

Also the leds may be acting weird because this schematic is wrong. As you can see one of the led's anode isn't connected to ground. It's circled in red.

If you really want it to return something you could use this:

long int timeLoop (long int startMillis, long int interval){ // the delay function

    while(millis() - startMillis < interval){}
    return millis() - startMillis;
}

But it really isn't needed.


Maximum sampling rate of Arduino Mega2560 I'd like to know what is the maximum sampling rate achievable while using ADC on Arduino Mega2560.

Thanks

The beginning of section 26 of the datasheet for the ATMega2560 gives the following data:

  • 13µs - 260µs Conversion Time
  • Up to 76.9kSPS (Up to 15kSPS at Maximum Resolution)


Not getting any output from ECG sensor AD8232 I am trying for the beginning to run a simple Arduino code in order to test the functionality of the ECG sensor. What I am getting on the output are some random values around 600 or around 200.
I connected everything the same as in any tutorial about AD8232:
GND -> GND, 3.3V -> 3.3V, L0+ -> digital pin 10, L0- -> digital pin 11, output -> analog pin A0.
I placed the sensor pads on my body like in pictures (forming a triangle), but regardless of putting the electrodes or not, I always get the same floating signal.
Here is Arduino code:

int ecg;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(10,INPUT);
  pinMode(11,INPUT);

}

void loop() {
  if((digitalRead(10) == 1)||(digitalRead(11) == 1)){
    Serial.println('!');
  }
    else{
    // send the value of analog input 0:
    Serial.println(analogRead(A0));
    }
    //Wait for a bit to keep serial data from saturating
    delay(1);
}

When I run this code I get only "!" on the output, no matter where I put the electrodes on my body. When I comment "if" and "else" parts of the code and print directly only reading from the pin A0, I get those random floating values, like on the image.

I also tried another custom built ECG sensor, but the results are the same. I haven't found the solution anywhere. It is not about the noise, because when I touch the metal box of my PC, I only reduce the values but there is still nothing on the output.

The problem was that I connected GND on the other half of the protoboard and there was no connection. I thought that the whole length of the protoboard is on the same potential for + and -, so GND wasn't connected. After connecting GND pin correctly, all worked perfectly.


Arduino, 74HC595N, magic Good day

I'm playing with Arduino and shift register chip 74HC595N and already tried many different ways to solve my problem, but still to luck :(

So that is my current simple scheme:

Arduino 2,3,4 ports connected to data, clock and latch pins of 74HC595N. I've connected only first two output pins of chip to make minimum power consumption and to simplify this example as much as possible.

That is my sketch:

const int latchPin = 4; //Pin connected to ST_CP of 74HC595
const int clockPin = 3; //Pin connected to SH_CP of 74HC595
const int dataPin = 2;  //Pin connected to DS of 74HC595

void setup()
{
  Serial.begin(9600);
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(13, OUTPUT);
}

void loop() {
  Serial.println("ON");
  digitalWrite(13, HIGH);
  send(B10000001);
  Serial.println("OFF");
  digitalWrite(13, LOW);
  send(B01000010);
}

void send(byte d) {
  Serial.println(d);
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, d);
  delay(1000);
  digitalWrite(latchPin, HIGH);
}

And the problem is: sometimes leds are blinking but very unstable. Sometimes it's not working at all, sometimes only first led is blinking, but second one is not. Sometimes opposite - second led is blinking, first one is not. Sometimes one of led is blink very fast (just flash instead of 1 second delay).
If I touch wires and elements on breadboard - something changing. Even without touching anything - situation changing. It seems like problem is somewhere in connection or power supply and I've already tried to except it: tried few different breadboard, two different 595 chips, different wires and resistors, tried Arduino Uno, Mega and nano. Even tried atmega328p standalone, tried power it from USB, from 9v battery, old mobile charger (5.4V, 650 mA), tried to power arduino with external source (12V, 1A). In all cases the problem still exists.

I've already read a lot about power supply for Arduino, but I think at least few of the ways I've already tried to supply power is good enough for 595 chip and two LEDs - isn't it?

Please, advice me what else can I try?

Even this is quite old, to help others as well:

As you already did, pin 13 (output enable, active low) to ground and pin 10 (master reset, active LOW) to HIGH, to disable reset.


Rotating a motor with L293D I'm following this tutorial to control a DC motor with an Arduino.

I have the same problem as this stackexchange post arduino.stackexchange.com/questions/10049/problems-with-l293d where the motor is not rotating.

The chip is heading to the right. (5v pins are on the right)
Connecting directly the motor to the battery works.
Current (5V on the bottom & 2*1.5V) is flowing everywhere expected EXCEPT on the yellow & green wires of the motor (the red wire of the battery pack is connected to the second line of the breadboard).
Connecting directly the motor to the battery works.
I copied the code of the above tutorial which is basically : "digitalWrite(4,HIGH);", there is current on the cable.

Am I wrong into thinking that a L293D chip can output sufficient current ? Is the chip malfunctioning ?

Your picture shows a holder for two AA cells, yielding something in the neighbourhood of 3v.  That is far too little for an L293D.  (This isn't really your fault, as it appears you got this erroneous idea from following a bad tutorial, but it does demonstrate that not everything you read on the Internet is sensible.  Using a 9v "transistor" battery is also a bad idea).    3 cells would be about the minimum, but even there it would not work well, as that chip has two bipolar transistors in the path yielding a voltage drop of over a volt.

To use a an L293D you really want at least a 5 or 6 volt system, and a motor wound for low to moderate current at that voltage.

If you want to use a lower voltage, look at a more modern MOS-based H bridge chip - the TB6612FNG is an often used example.  You will however still want to choose motors wound for moderate current at a 3- or 4- cell voltage - those intended for 2-cell usage typically draw more current than is ideal for an IC driver chip.

It is entirely possible that there are additional issues with your attempt as well.  Normally, a question such as this would require a complete and accurate schematic diagram, which you have not provided.


Come out of loop and execute Setup again I want to end loop at a specific time and start setup again. Is this possible? (I can explain reason in case you require).

You could just call setup() yourself:

void loop() {
    if (some_condition) {
        setup();  // reinitialize everything
        return;
    }
    // etc.
}

But, as Majenko puts it, if you nee to do that it looks like there is
something wrong with your methodology.

That being said, it would be less suspicious if you only need to
reinitialize some specific part of your program. In this case you can
make a separate function for these initializations, and call it both
from setup() and, when needed, from loop():

void init_foo() {
    // ...
}

void setup() {
    init_foo();
    // other initializations...
}

void loop() {
    if (some_condition) {
        init_foo();  // reinitialize foo
        return;
    }
    // etc.
}


How to use Arduino Pro Mini without Programmer I'm a software engineer, but I'm not too skilled at understanding hardware design yet. I'm trying to learn how to use an Arduino Pro Mini board without the programmer connected, so I can actually make fun toys, etc. Currently, the software will only run when connected to the programmer (or at a minimum with the SCK pins connected to each other). I have been searching online for days, and I think I need a crystal or resonator hooked up somehow, but I can't figure out how to hook them up (which pins). I bought 5 16 MHz ceramic resonators, and I have them right here with me, but I can't find the answers online how to hook it up and have the board run stand alone. Any ideas? Thank you in advance.

You might be on the wrong track.

You do need a crystal (or not, it depends on), and an Atmel programmer if you want to program an empty chip.

However, all Arduino boards come with a chip pre-programmed with a bootloader.
Then it is rather easy: you need an FTDI cable to connect the board to a PC. Then run Arduino IDE on the PC. (The FTDI cable is actually an USB-to-serial converter.)

The Arduino IDE lets you edit a C like code, complile it to binary, and send it out via the FTDI cable to the serial port (Rx, Tx) of the board. The microcontroller on the board comes with a bootloader. Bootloader is a small program which runs at power up, and will receive the data from the computer and put your program to the microcontroller. Then your program will run on the microcontroller.

So, you don't need an external programmer.

On the other hand, you may consider picking a different Arduino board. Arduino Micro, or Pololu A-star Micro (for half of the price of the Arduino Micro) offers a board with a direct USB connection. All you need is one USB cable.

These boards come with a much better microcontroller (32u4) which has a hardware USB connection (allowing you to make a mouse or a keyboard, and control PC (such as buttonbass.com) from your gadget).


How to update the character table of MAX7456 I've got a MAX7456 chip and I am using this library with it.
But the issue is that the character table is not the one the library needs to function like it should. The "Hello world" example is nowhere near to what it should display, because the character table is wrong.

All the instructions that talk about character set updating require a USB FTDI cable (I don't have one), I am able to  program the board with USBASP programmer but that's it. I also have a few Nanos, if that helps.

How could I update the character table to what the library needs (without a FTDI cable) or how to make the sketch included to update the character set work properly?

To solve this problem one would need to get the builtin character updating sketch work (Max456WriteTable.cpp in examples folder). After the sketch has been compiled one would have to connect either FTDI cable or a USBASP programmer to the board and upload the sketch to it.

The character set (array) itself used in the code can be updated with the appropriate program available at this site.

UPDATE: In the end I solved it this way.

Many thanks to Charlie Hanson & Nick Gammon.


MAX7219 7-segment 8-digit display in wrong order I have daisy-chained three MAX7219 7-segment 8-digit displays and wired it according to this diagram:

but no matter what library I use, the middle segment is in the wrong order when I display it.

So the numbers "123456789123456789"

would display as"12345678 76543219 89"

What could be wrong?

If you had three separate boards that you had chained together I would be surprised if one of them was wrong, but looking at the picture it looks like one board and I would think it was more likely that one display was incorrect.

I can't see your code, so I can't say if there is a bug in it or not.  It is possible that you have done something unusual, you might want to post a MINIMAL example to let people give it the once over.

As far as I know there aren't any "configuration settings" on a Max7219 to cause the affect you are seeing.  The fact that the 3rd display is correct implies that the tracks on the PCB are correct and its the IC that's got its wiring backwards, but that's a daft idea.

You might be able to work out if a track is wrong, or such like, but it would be so much easier to fix in software.  When you write to the display add an extra function that traps calls to the middle segment and flips the digits round (so tmp == digit[7]; digit[8] == digit[0]; digit[0] = tmp; // You know what I mean).


Using digital weighing scales with INA125p Complete electronics beginner here. I'm attempting to build a weighing scale with an Arduino.

I'm attempting to follow this tutorial, with the shield that they use.

I've arranged my load cells on the scale into a Wheatstone Bridge, and I can get some readings just by taking a voltage reading from the two cells marked V+ and V-. The board has terminals that are linked to a INA125p, and the pins should give an amplified reading.

Pin A1:0.96
Pin A2:1.42
Pin A3:5.00
Pin A4:5.00
Pin A5:5.00

Regardless of whether I have the scale wired in or not, I get these readings from the individual pins. The scales seem to be able to take power from the Arduino shield.

The scales that I have are different from the ones in the example. From what I can figure out, the yellow cables that they reference turn their particular scale on when weight is put on it.

I've put the wires where I take the reading into the 2 and 4 terminals on the circuit board that they have (where the tutorial references a differential signal), but again, it makes no change.

  unsolder or cut the white wire that is referred to as G3 (Wheatstone bridge mass) on the original printed circuit, extend take it to terminal 1 on the new printed circuit;

  unsolder or cut the white wire that is referred to as G2 (Wheatstone
  bridge positive) on the original printed circuit, extend take it to
  terminal 3 on the new printed circuit;

  unsolder or cut the white wire that is referred to as G1 and G4 on the
  original printed circuit, extend take it to terminal 4 and 2 on the
  new printed circuit (differential signal on the Wheatstone bridge)

I've attempted lots of different combinations of cables and terminals on the new circuit, but it appears to make no difference to the readings.

My question is:
Based on the tutorial and the drawing above, am I taking the readings from the correct place? Are there any things I'm obviously doing wrong with the circuit itself?
If the circuit is correct, how would I go about trying to get correct readings from the scale when I add weight to it?

I apologise for the vague nature of this question, but I am a complete beginner trying to figure this out, and I am struggling to follow the tutorial. I'll try and provide any additional information that you need.

EDIT - I have a Salter SAL-3003 SSSVDR08 scale.

Each load cell has 3 cables, Red, Black and White. The red ones are the ones marked with the V+, V- etc. On the original board, they were wired in threes.

Fixed (to some extent)! Faulty connection between the INA125p and the plint it was sitting in. I refitted it and i'm now getting varied readings with the scales, but that's to be expected with the noise the INA125p generates.


Sample code for using adafruit servo shield? I would like to control 16 motors with a servo shield, however, I have found scant to nothing sample code online. The one I was able to find is...strange to say the least

https://github.com/kachok/arduino-libraries/blob/master/Adafruit_PWMServoDriver/examples/servo/servo.pde

#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

// called this way, it uses the default address 0x40
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

#define SERVOMIN  150 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  600 // this is the 'maximum' pulse length count (out of 4096)

uint8_t servonum = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("16 channel Servo test!");

  pwm.begin();

  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
}

void loop() {
  // Drive each servo one at a time
  Serial.println(servonum);
  for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++) {
    pwm.setPWM(servonum, 0, pulselen);
  }
  delay(500);
  for (uint16_t pulselen = SERVOMAX; pulselen > SERVOMIN; pulselen--) {
    pwm.setPWM(servonum, 0, pulselen);
  }
  delay(500);

  servonum ++;
  if (servonum > 15) servonum = 0;
}

Im used to controlling motors using servo.write, but with the shield, it doesn't seem very intuitive as to how I should control the motors. How does Servomin and Servomax map to 0 degree and 180 degree?

Someone please elucidate!

Adafruit's guide for the shield is here:
https://learn.adafruit.com/adafruit-16-channel-pwm-slash-servo-shield/using-the-adafruit-library

I'm not sure how much the library you linked and the official one differ. They seem to be used the same way, but you should probably stick with the official one.

You are going to have to use setPWM(pin, on, off) since the arduino is not generating the signals like it would with servo.write(), the arduino is sending commands to a chip on the shield that generates the signals for you.

Adafruit recommends calibrating SERVOMIN and SERVOMAX yourself with whatever brand of servo you plan on using, but those default values should be pretty close.


ESP8266 (D1 mini) fails to upload sketches My Setup: 3.3v LiFePo battery attached to G and 3.3 pins. Serial-USB connected.

Result: During the following code the blue on-board LED blinked rapidly for a few seconds then went off. I unplugged it to see if it was programmed but the Blink Sketch didn't run. Any help would be greatly appreciated.

Sketch uses 222,205 bytes (21%) of program storage space. Maximum is 1,044,464 bytes.
Global variables use 31,572 bytes (38%) of dynamic memory, leaving 50,348 bytes for local variables. Maximum is 81,920 bytes.
C:\Users\jhoxie\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.9/esptool.exe -vv -cd nodemcu -cb 115200 -cp COM3 -ca 0x00000 -cf C:\Users\jhoxie\AppData\Local\Temp\arduino_build_351972/Blink.ino.bin
**(Everything below this line was highlighted in red)**
esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to nodemcu
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
Uploading 226352 bytes from C:\Users\jhoxie\AppData\Local\Temp\arduino_build_351972/Blink.ino.bin to flash at 0x00000000
    erasing flash
    size: 037430 address: 000000
    first_sector_index: 0
    total_sector_count: 56
    head_sector_count: 16
    adjusted_sector_count: 40
    erase_size: 028000
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    setting serial port timeouts to 15000 ms
    setting serial port timeouts to 1000 ms
    espcomm_send_command: receiving 2 bytes of data
    writing flash
................................................................................ [ 36% ]
................................................................................ [ 72% ]
..............................................................                   [ 100% ]
starting app without reboot
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
closing bootloader
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete

Thank you for your input. Especially the tip on connecting the battery while connected to usb [tttapa] I finally got it to work by changing the baud rate and messing around with the settings(i.e. board in IDE). I believe I got it to work with the "WeMos D1 R2 & Mini" board whereas I was using the generic esp8266 board.


Accessing one code using another code on RobotDyn Uno+WiFi board Ok so I've been trying to do this for quite some time now. Still couldn't get it to work. I am trying to read a ESP8266 WiFi program from a normal Arduino Uno program. I've seen some people do this:

#include <SoftwareSerial.h>

Then

SoftwareSerial esp8266(2,3);

Let me see a working example of this?

Thanks for everything.

You can't 'access code'. You can write sketches to communicate for example over Serial or SoftwareSerial. You connect the pins of Serial interfaces RX to TX and let sketch in one MCU read or parse what the sketch in other MCU sent over Serial with print or write.
The onboard connection on Uno+WiFi board is over Serial. So you can't use USB and connection to esp8266 at the same time. But you could use SoftwareSerial like other use it with esp8266, if you connect some pins (for example 6 and 7) of Uno headers to Serial of esp8266 which is accessible on the esp8266 header on the board.


Trying to measure distance using an ultrasound sensor I am relatively New to Arduino and need your help. Actually i made a code and the problem is that the ultrasound sensor doesn't work at all. It isn't displaying the distance between the object and and the sensor. Can you help me please!
Here is my code:

note: the code has some motor cotrol commands

int enableBridgePin = 10;
int forwardPin = 11;
int backWardPin = 9;
int tickPin = 2;
const int trig = 5;
const int echo = 6;

int dt;
int distance;

float rotationSpeed[50];

void setup() {
  pinMode(enableBridgePin, OUTPUT);
  pinMode(forwardPin, OUTPUT);
  pinMode(backWardPin, OUTPUT);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  Serial.begin(9600);

  digitalWrite(forwardPin, LOW);
  digitalWrite(backWardPin, LOW);

  interrupts();
  digitalWrite(enableBridgePin, HIGH);
}

void loop() {
  analogWrite(enableBridgePin,255);

  digitalWrite(forwardPin, HIGH);
  digitalWrite(backWardPin, LOW);

  distancefonction(dt, distance);
  if(distance>5){
   detachInterrupt(digitalPinToInterrupt(tickPin));
   digitalWrite(forwardPin, LOW);
   }

}

int distancefonction(int dt, int distance)
{
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  dt = pulseIn(echo, HIGH);
  distance = 0.034/2*dt;
  Serial.println(distance );}

You have declared int distance outside of any method. That means it's available from all methods. Some people call it a global variable.

However, you have a method int distancefonction(int dt, int distance) which receives int distance as a parameter. This results in an ambiguity: if you refer to distance within the method like

distance = 0.034/2*dt;

should this now refer to the parameter distance or the global variable distance?

The answer is: you can't decide. The C/C++ standard has decided for you and the answer is: the parameter will take precedence and thus hide the global variable. This thing is also called "shadowing".

What does it actually mean?

The global variable distance has an undefined value at the start of the program. Let's assume the value is 0.
distancefonction() is called, passing distance as a parameter. This will create a copy of the value 0 on the stack.
the function will calculate the distance and update the variable on the stack.
The Serial.println() statement within the function accesses the variable on the stack and will print the correct distance.
Once the function is complete, the code in loop() will access the global variable distance, which still has the old value, because only a copy has been updated.

What is the solution?

Of course there are several solutions.

The simplest fix is probably to remove the parameter int distance from distancefonction. Thus the function will not receive a copy and instead operate on the global variable.
Another solution is to let distancefonction return the actual distance. The method signature already indicates that you wanted to return a value: the intfrom int distancefunction(...) says that. At the moment, the function does not return anything. You could write return distance; at the end. This approach could eliminate the global variable completely.


Getting an error while uploading a code to the Arduino when ethernet shield is attached I bought ethernet Shield today and connected it to Arduino Uno, now when I try to upldoad I get the following error, however if I remove the shield from the UNO it works fine.

Sketch uses 10,486 bytes (32%) of program storage space. Maximum is 32,256 bytes.
Global variables use 661 bytes (32%) of dynamic memory, leaving 1,387 bytes for local variables. Maximum is 2,048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

Is it something wrong with he ethernet shield ?
Ethernet is not plugged in but even when i plug in the ethernet wire the indicators at Jack does not lit up

I fixed the problem by cleaning the soldering near the SD card slot on ISCP, see image below.


Make one button print different sentences on LCD I am very new to arduino and I've been scratching my brain on how to make one button print out three different sentences. When I press it the first time, a " I am " is suppose to appear, when I press it the second time " very" and then the third time " late". I can't have three different buttons because a tone follows this button as well.

Consider using what is commonly called in programming as a Finite-state machine.  Advance to the next state each time the button is pressed.  Start out with 3 states and advance to the next after pressing the button.  You many need to double the number of states after adding your message to the program.  This is because you will want to press the button and only print the message once then advance to a new state where all you do is wait for the next button press.

Note, a mechanical device such as a button will need to be de-bounced either in hardware or in software.  This is because the processor may see individual makes and breaks as the button is closed and opened causing it to advance to the next state in unexpected ways.


How can I send serial over RF? I've got the following:

#include <SoftwareSerial.h>

const int rx = -1;
const int tx = 4;

SoftwareSerial mySerial(rx, tx);

void setup()
{
  mySerial.begin(2400);
  pinMode(tx, OUTPUT);
}

void loop()
{
  if(mySerial.available())
  {
    String data = "Hello World";

    for(int k = 0; k < data.length(); k++ )
    {
      mySerial.write(0xAA);
      mySerial.write(data[k]);
    }

    mySerial.write(0xA9);
  }

  delay(1000);
}

Which I'm trying to send to to a RF transmitter module. It all compiles just fine, but am I forgetting something? And does pin 4 = physical pin 3?

In your loop function you have:

if(mySerial.available())
{
  String data = "Hello World";

  for(int k = 0; k < data.length(); k++ )
  {
    mySerial.write(0xAA);
    mySerial.write(data[k]);
  }

  mySerial.write(0xA9);
}

The available() function returns the number of bytes available in the receive buffer. You say your module is a transmitter, so there will never be any data to receive (I can see the module doesn't even have a tx pin). Hence you will never transmit any data.

That said it's not a good idea to send data plain over wireless. It might work to some extent, but you'll likely get much more lost data. Look at the virtual wire library or google "manchester coding" if you wan't to roll your own.


I2C or SPI to control 6 motors? I am a hobbyist & know little about electronics.

I am making a robot arm, like this one. For which I will need 2 stepper motors (for elbow & shoulder joint) & 4 simple DC motors.

Which means I will need to allocate a lot of pins on my board (Uno).

So I was just reading about I2C & then eventually SPI. My question is:

Is it possible to control 6 motors (or atleast 2 steppers) with I2C or SPI (assuming the motors are powered by seperate source), if so can you point me to someone's example code.
If not possible, how do I overcome the shortage of pins, because I have already dedicated them to many sensors.

For the stepper motors, the easiest way to work with them is by using a very common A4988 board which is widely used with 3D printers. The controls are very easy and for them I send you this question which I answered some time ago.

Then, you say that you haven't got a lot of connections left on your UNO board, so I think that SPI would't be very useful, as it takes 3 pins for the data transmission (SCLK, MOSI, MISO) plus one pin for every device you connect.

The best way (even if it is a little slower that SPI) is to use I2C, which needs that you leave unused analog input pins A4 and A5, as they are the I2C BUS. Unfortunately I haven't any knowledge about I2C DC motor drivers.

For the steppers, I suggest to take a look at this, but it depends by your budget for what you can buy.

You could fix the pin shortage problem by adding some 74HC595 shift registers. They aren't very expensive (less than a dollar, or if you live in europe, .5€) and they can be daisy-chained. To control them, see the Arduino website tutorial.

Finally, if the pins that you use are inputs, use a 74HC165, which is the opposite of a 595. As always, see the Arduino website tutorial.


Why do only specific arduinos support the keyboard and mouse libraries? The Arduino website suggests that only three boards are supported for the Mouse and Keyboard library page:

Leonardo
Micro
Due

What is special about those boards, that the other boards in the Arduino family don't have? I thought they might have the same proceesing chip on them but only two of them do. The CPUs are correspondingly:

ATmega32u4
ATmega32u4
Atmel SAM3X8E ARM Cortex-M3

I have Nanos, Unos and Duemilanoves. I am out of luck aren't I?

So my question is: what do those three boards have that lets them support those libraries?

Those chips have hardware support built into them to handle the rather strict timing requirements for interpreting (and responding to) USB sequences. You will notice, for example, that on the Arduino Uno there is a second chip (the Atmega16U2) which also can handle USB. In fact the chips with a "U" in the name generally can do this.

  I have Nanos, Unos and Duemilanoves. I am out of luck aren't I?

You have a couple of options. Some people reflash the USB chip on their Uno (for example), although personally I think that is a bit fiddly.

Alternatively, there is a library called VUSB (virtual USB) which lets you do some USB on the non USB chips. Google vusb arduino.

You need three resistors and two zener diodes to make up the hardware that lets this library do its stuff.


LCD5110 - How to make Direct Draw via 2D-array of boolean? How to draw 2D-array directly on LCD 5110 (PCD8544)?

I have tried libraries like AdaFruit and several others.

But I need draw there via pixel 2D-array, something like this:

bool picture[48][84] = {
 {0,1,0,0, ... to 84 elements},
 {1,0,1,0,0, ...},
 ... to 48 elements
};

I haven't used charset table or geometry figures drawing library functions. Simplest and smallest drawing by pixel - 0 - not draw, 1 - draw pixel.

The "picture bitmap" will generate on the mini-pc board via Python and send to Arduino, which will draw it as "video card".

What is the simplest way to draw pixel in any site of the display without using powerful libraries?

Something about this:

// Send boolean bitmap 48x84 to LCD 5110
// Rows
for (int i=0; i<48; i++) {
 // Columns
 for (int j=0; j<84; j++) {
  // PIN 5 is Din on the 5110 module
  digitalWrite(5, picture[i][j]);
 }
}

For a start the Arduino Uno is incapable of storing that array in RAM. You're using twice as much memory for that array as the Arduino has in total. You will have to place it in PROGMEM and use the right functions to access it.

Secondly, you have to use a special library to control the display properly. That library will contain functions to draw on the screen. So your function to draw it would look something (though not exactly) like this:

const bool picture[] PROGMEM = {
    1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0,
    ... etc ... ... 4032 numbers in total ...
};

for (int i=0; i<48; i++) {
    for (int j=0; j<84; j++) {
        lcd.setPixel(j, i, pgm_read_byte_near(picture + (i * 84 + j));
    }
}

Refer to the manual for the library for the actual function to run and how to configure and set up the LCD screen.


What are the steps involved in porting an Arduino library? I want to use the Adafruit CC3000 and its Arduino libraries on another platform. In this case it's the Arduino pin compatible PSOC4 Pioneer Kit. This is an ARM Cortex M0 based platform.

My question is: How would I go about porting a library like this? What are the steps, key files etc?

One obvious issue is that PSOC Creator does not readily support C++.

One positive might be that the Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU.

NOTE: If you think this question is off topic; please head over to this question on Arduino Meta to voice your opinion on whether questions on Arduino Compatible devices are appropriate for this list.

I did essentially the same thing with getting the Adafruit ST7735 library working in chipKIT. I started a support thread here which can lead you through my process.

I tackled it the same way I do general programming:
1-» Copy over Libraries, get it so your compiler can actually SEE them.
2-» Start trying to compile and then triage errors from the "top level" down:
3-» Look for stlib functions you recognize as should be working and fix those.
4-» Look for AVR specific code and comment those out. I normally also add my initials and a comment: ckck - bitbanging SPI, so I can search for these later.
Repeat 3 and 4 until it works or you quit. :)

Reach out to the forums for your target; they might have been there done that -- or like in my case, you introduce them to something that they want, so they dive in and help.


bluetooth module with stk500_recv() error I am trying to dow what is demonstrated in this tutorial. I have altered the original setup a little by adding a level converter to not fry the Bluetooth module and resistors for the LEDs, as well as using only 2 instead of four LEDs (which I adjusted for in code later). other than that I am using the exact same setup, code,and procedure. Yet when I try to run my code on the Arduino. I get the error below. I believe it is due to using Tx/Rx and serial at the same time but I really don't know anything about this. Should I add more libraries?
Should I change the wiring shown in the tutorial link? It seems like I need to use Tx/Rx

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xce
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xce
avrdude: stk500_recv(): programmer is not responding

Here is the code I used from tutorial:

//Coded By: Angelo Casimiro (4/27/14)
//Voice Activated Arduino (Bluetooth + Android)
//Feel free to modify it but remember to give credit

String voice;
int
led1 = 2, //Connect LED 1 To Pin #2
led2 = 3, //Connect LED 2 To Pin #3
led3 = 4, //Connect LED 3 To Pin #4
led4 = 5, //Connect LED 4 To Pin #5
led5 = 6; //Connect LED 5 To Pin #6
//--------------------------Call A Function-------------------------------//
void allon(){
     digitalWrite(led1, HIGH);
     digitalWrite(led2, HIGH);
     digitalWrite(led3, HIGH);
     digitalWrite(led4, HIGH);
     digitalWrite(led5, HIGH);
}
void alloff(){
     digitalWrite(led1, LOW);
     digitalWrite(led2, LOW);
     digitalWrite(led3, LOW);
     digitalWrite(led4, LOW);
     digitalWrite(led5, LOW);
}
//-----------------------------------------------------------------------//
void setup() {
  Serial.begin(9600);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);
}
//-----------------------------------------------------------------------//
void loop() {
  while (Serial.available()){  //Check if there is an available byte to read
  delay(10); //Delay added to make thing stable
  char c = Serial.read(); //Conduct a serial read
  if (c == '#') {break;} //Exit the loop when the # is detected after the word
  voice += c; //Shorthand for voice = voice + c
  }
  if (voice.length() > 0) {
    Serial.println(voice);
//-----------------------------------------------------------------------//
  //----------Control Multiple Pins/ LEDs----------//
       if(voice == "*all on") {allon();}  //Turn Off All Pins (Call Function)
  else if(voice == "*all off"){alloff();} //Turn On  All Pins (Call Function)

  //----------Turn On One-By-One----------//
  else if(voice == "*TV on") {digitalWrite(led1, HIGH);}
  else if(voice == "*fan on") {digitalWrite(led2, HIGH);}
  else if(voice == "*computer on") {digitalWrite(led3, HIGH);}
  else if(voice == "*bedroom lights on") {digitalWrite(led4, HIGH);}
  else if(voice == "*bathroom lights on") {digitalWrite(led5, HIGH);}
  //----------Turn Off One-By-One----------//
  else if(voice == "*TV off") {digitalWrite(led1, LOW);}
  else if(voice == "*fan off") {digitalWrite(led2, LOW);}
  else if(voice == "*computer off") {digitalWrite(led3, LOW);}
  else if(voice == "*bedroom lights off") {digitalWrite(led4, LOW);}
  else if(voice == "*bathroom lights off") {digitalWrite(led5, LOW);}
//-----------------------------------------------------------------------//
voice="";}} //Reset the variable after initiating

How did you upload the sketch? With the Bluetooth module still connected? In that case please disconnect it and the upload. Connect again after the upload.


Execute Code While Refreshing a 7 Segment LED Display I'm using the following library to drive a 4 digit, 7 segment LED display:

http://playground.arduino.cc/Main/SevenSegmentLibrary

The display is showing the temperature which it gets from a DS18B20 temperature sensor.  Since the LED display constantly needs to be refreshed, when the code runs to get the current temperature, the display temporarily turns off because the LEDs are not being refreshed.  The code I am using is below. Is there anyway to prevent the LED display from turning off while the temperature request code runs?

#include <SevSeg.h>
#include <OneWire.h>
#include <DallasTemperature.h>

SevSeg sevseg;

unsigned long timer; // the timer
unsigned long INTERVAL = 30000; // the repeat interval (30 seconds)

#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup() {
  byte numDigits = 4;
  byte digitPins[] = {A2, A3, A4, A5};
  byte segmentPins[] = {8, 10, 6, 4, 3, 9, 7, 5};

  sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
  sevseg.setBrightness(90);

  // Get the initial temperature and show it on the LED display
  sensors.begin();
  sensors.requestTemperatures();
  sevseg.setNumber(sensors.getTempCByIndex(0), 1);
  timer = millis(); // start timer
}

void loop() {
  if ((millis()-timer) > INTERVAL) {
    // Reset the timer and get/display the current temperature
    timer += INTERVAL;
    sensors.requestTemperatures();
    sevseg.setNumber(sensors.getTempCByIndex(0), 1);
  }

  sevseg.refreshDisplay(); // Must run repeatedly to refresh the LED display
}

The problem here is that the display is driven using a timer interrupt.  The temperature sensor, being a one-wire device, has to have very careful timing to communicate with it.  As a result it disables interrupt so it has exclusive use of the CPU and can properly predict its timing while it's communicating.  And so the display can't refresh at the same time.

So what can you do?  Well, nothing really.  You can't have perfect timing for the temperature sensor while at the same time interrupting it for displaying the value.

So there's really two main options:

Change the temperature sensor.  Use an SPI or I2C temperature sensor that has a real hardware interface to communicate with it so you don't have to use big-banging.
Change the display.  A non-multiplexed display or a display with its own built in driver (most often with some serial protocol like I2C or UART) would mean you don't have to use interrupts to update the display.

Basically you have two technologies that won't sit together well on the same chip.

Update:

I missed the sevseg.refreshDisplay() function call since the website had scrolled it off the bottom of the code block.  Bah!

Ok, so it's not using an interrupt.  That could be a good thing, or it may be meaningless.  It takes time to do the temperature reading, and it's that getting in the way of the refreshing.

There's a chance you may be able to push the update "into the background" by attaching it to a timer interrupt, but if the OneWire communication does disable interrupts then the problem will still persist (I don't have OneWire to hand to look at the code right now).


Arduino recieve sensor data from other arduino SPI I have Arduino Uno (sender) and Arduino Uno Wifi rev 2 (receiver). I want to send the ping value to the other one via serial - jumper wires.
Arduino Uno is using the newping example, and I want the Uno Wifi to receive the sensor value and print it to serial.
I am using SoftwareSerial.h
jumper wires go TX<->RX , RX <->TX, GRD-GRD according to the pins in the sketch below.
The problem is the sketch code for the Uno WiFi (receiver), it keeps printing garbage and seems like no carriage return sometimes.
13
⸮10
⸮52
⸮5LC⸮1⸮H⸮10
5⸮H⸮51
13C⸮10
⸮5⸮H⸮5LC⸮13
10
⸮52
51C⸮13
10
⸮52
5LC⸮13
⸮10C⸮52
⸮51
13
10
⸮52
50

Code on Uno (sender):
// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------
#include <SoftwareSerial.h>
#include <NewPing.h>

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
SoftwareSerial mySerial(9, 10); // RX, TX

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

 Serial.println("Hello World Serial");
 mySerial.begin(4800);
 mySerial.println("Hello World, mySerial");
}
void loop() {
  delay(500);                     // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
  mySerial.print(sonar.ping_cm());
  mySerial.println();
  }

code on uno wifi (reciever):
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  // set the data rate for the SoftwareSerial port
  mySerial.begin(4800);

}

void loop() { // run over and over

    Serial.println(mySerial.read());
    delay(1000);

}

I can see the Uno (sender) with NewPing is printing the correct data to it's serial but I can't get the Uno wifi (listener) to get the same value. Its just garbage. I am new to this, what am I doing wrong?

Well had a bit of luck after spending all day on this.
Arduino UNO (sender): Like mentioned by chrisl, use Serial.write and not Serial.print
mySerial.write(sonar.ping_cm());

UNO Wifi (receiver):
Serial.println(mySerial.readString());

So, instead of mySerial.read I used mySerial.readString.
This is most likely a obvious mistake to almost everybody here; took me two days. Sigh.


How to execute three functions at the same time? How to implement three functions, which can execute in the same time (function of input random variables)?

You can implement three functions but you can't able to execute them same time.


Differences between Arduino Uno SMD and Uno DIP I just bought an Arduino Uno (SMD version) from W11Stop and want to know whether there is any other difference between Arduino UNO DIP and Arduino UNO SMD besides knowing that the SMD version doesn't have a DIP chip which can be replaced?

I am just a beginner so please help me if I am wrong!

As far as I know there is no real difference, at least not directly related to the SMD.

There are many clones which sometimes have slightly different behavior or protection.

But for the SMD the only disadvantage is it cannot (easily) be replaced.

I have one original one (with DIP) and several clones and so far I did not found any difference, except for having mini USB instead of normal USB.


What datatype is the names of the analog inputs? I am writing a code for an automatic garden, and for this, I will use an array of sensors. I want to represent each plant as a class, and so one of the private variables will then be the sensorID, the name of the input on the analog inputs. But these are called 'A0' 'A1' and so forth, so I am wondering what datatype they are?

class Plant{
private:
String name;
??? sensorId;
...
public:
readSensor(??? sensorId);
...
};

I want to standardize this so I don't have to physically write 'A0' or 'A1' each time I need to read the sensor.

They're uint8_t:

static const uint8_t A0 = 14;
static const uint8_t A1 = 15;
static const uint8_t A2 = 16;
static const uint8_t A3 = 17;
static const uint8_t A4 = 18;
static const uint8_t A5 = 19;
static const uint8_t A6 = 20;
static const uint8_t A7 = 21;

Those are defined in the pins_arduino.h file in the board's variant folder.


Rc switch library transmit using protocol 5 I'm trying to transmit using mode 5 with the rc switch library, but my reciever tells me that the data is using protocol 2. I'm using the RecieveDemo_simple example as a sniffer for 433 MHz and I'm recieving data with protocol 5 from a wireless electric plug that I want to replicate.

I am able to send the data, but it is using the wrong protocol most of the time.

Here's some output from the reciever:

Received 15766156 / 24bit Protocol: 2
Received 15766156 / 24bit Protocol: 5
Received 15885740 / 24bit Protocol: 2
Received 15885740 / 24bit Protocol: 2
Received 15766156 / 24bit Protocol: 2
Received 15766156 / 24bit Protocol: 2
Received 15766156 / 24bit Protocol: 5
Received 15885740 / 24bit Protocol: 2
Received 15885740 / 24bit Protocol: 2
Received 15885740 / 24bit Protocol: 5

The code:

/*
  Example for different sending methods

  https://github.com/sui77/rc-switch/

*/

#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {

  Serial.begin(9600);

  // Transmitter is connected to Arduino Pin #10
  mySwitch.enableTransmit(10);

  // Optional set pulse length.
  // mySwitch.setPulseLength(320);

  // Optional set protocol (default is 1, will work for most outlets)
  mySwitch.setProtocol(5);

  // Optional set number of transmission repetitions.
  // mySwitch.setRepeatTransmit(15);

}

void loop() {

  /* Same switch as above, but using decimal code */
  mySwitch.send(15885740, 24);
  delay(1000);
  mySwitch.send(15766156, 24);
  delay(1000);

}

I would expect your sending protocol 5 just fine.

But because protocol 2 and 5 are very similar, your receiver gets confused about which protocol it sees when there's noise or other interference.

This is the definition of the two protocols from the code:

{ 650, {  1, 10 }, {  1,  2 }, {  2,  1 }, false },    // protocol 2
{ 500, {  6, 14 }, {  1,  2 }, {  2,  1 }, false },    // protocol 5

Note the last three parts are the same, which are the pulses for 0, 1, and whether or not the high/lows are inverted.
The first part is also very similar, which is the pulse length. It's so similar that the difference probably falls within the margin for error the receiver software uses.
Only the second parts differs a bit more, which is the sync bit, it's a short high pulse followed by a longer low pulse. It's easy to mistake the one for the other though when there's noise and such.