Can't send Data to LCD1602 with I2C I've been doing fine with my LCD1602 I2C configuration but I discovered that command and data functions are the same even though I change the RS command/data bit, but the result is the same.

This is really strange, I really can't do anything about it??!

#define E   2   // E  bit
#define RW  1   // RW bit
#define RS  0   // RS bit

#define LCDadd_WR  0x4E
#define LCDadd_RD  0x4F

uint8_t bitmask = 0x08;
uint8_t i, arr[]={0x48,0x65,0x6c,0x6c,0x6f ,0x10 ,0x3a,0x29 ,0x10 ,0x48,0x6f,0x77,0x10
,0x61,0x72,0x65,0x10,0x79,0x6f,0x75,0x65,0x76,0x65,0x72,0x79,0x10,0x6f,0x6e,0x65};

// LCD prototypes
void LCD_Init(void);
void sendCMD(uint8_t CMD);
void sendData(uint8_t data);
void LCD_string(uint8_t arr1[]);
void move_cursor (uint8_t row, uint8_t col);

// I2C prototypes
void I2C_init(void);
void I2C_start(uint8_t address);
void I2C_stop(void);
void I2C_tx(uint8_t data);
void I2C_TWSR_Check(void);

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

void loop() {
//sendData(0x0E); /* I commented this line because it has the same effect as sendCMD(0x0F); in sendCMD function */
}

///////////////////////////////////////////////////
///////////////////////////////////////////////////
void LCD_Init(void)
{
  sendCMD(0x33);
  sendCMD(0x32);
  sendCMD(0x28);
  sendCMD(0x0F);
  sendCMD(0x01);
}

void sendCMD(uint8_t CMD)
{
  bitmask = 0x08;
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask &= ~(1<<RS));
  Serial.println("CMD");
  Serial.println(bitmask, HEX);
  I2C_tx(bitmask &= ~(1<<RW));
  I2C_tx(bitmask = CMD & 0xF0 | 0x08);
  _delay_ms(5);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  _delay_ms(1);
  I2C_tx(bitmask = (CMD<<4) & 0xF0 | 0x08);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  I2C_stop();
}

void sendData(uint8_t data)
{
  bitmask = 0x08;
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask |= (1<<RS));
  Serial.println("data");
  Serial.println(bitmask, HEX);
  I2C_tx(bitmask &= ~(1<<RW));
  I2C_tx(bitmask = data & 0xF0 | 0x08);
  _delay_ms(5);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  _delay_ms(1);
  I2C_tx(bitmask = (data<<4) & 0xF0 | 0x08);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  I2C_stop();
}

uint8_t BF(void)
{
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask &= ~(1<<RS));
  I2C_tx(bitmask |= (1<<RW));
  I2C_stop();
  I2C_start(LCDadd_RD);
  I2C_rx();
  while (!(TWDR == (bitmask & (bitmask<<3))));
  I2C_stop();
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask |= (1<<RS));
  _delay_ms(500);
  I2C_tx(bitmask &= ~(1<<RS));
  _delay_ms(500);
  I2C_stop();
}

void move_cursor (uint8_t row, uint8_t col)
{
  if (row==1)
  sendCMD(0x80+col);
  if (row==2)
  sendCMD(0xC0+col);
}

void LCD_string(uint8_t arr1[])
{
uint8_t cnt=0;
  for (i=0;i<29;i++)
  {
    sendData(arr1[i]);
    _delay_ms(500);
    cnt++;
    if (cnt==16)
    sendCMD(0xC0);
  }
  sendData(0x10);
}

///////////////////////////////////////////////////
///////////////////////////////////////////////////

void I2C_init(void)
{
  //set SCL to 100kHz
  TWSR = 0x00;
  TWBR = 0x48;
  //enable TWI
  TWCR = (1<<TWEN);
}

void I2C_start(uint8_t address)
{
  TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
  while (!(TWCR & (1<<TWINT)));
  TWDR = address;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
}

void I2C_stop(void)
{
  TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
}

void I2C_tx(uint8_t data)
{
  TWDR = data;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
}

uint8_t I2C_rx(void)
{
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

I2C_tx(bitmask |= (1<<RS));
I2C_tx(bitmask &= ~(1<<RW));
I2C_tx(bitmask = data & 0xF0 | 0x08);

RS is overridden in the third line, so the solution is:

I2C_tx(bitmask = data & 0xF0 | 0x08 | (1<<RS));

And delete the first two lines :)


how to simplify code I am as new as new can be to the Arduino world and have been playing around with them.  I have a few "Arduino Uno" boards that I purchased and have successfully loaded sketches to them.  However I am having problems figuring out how to write code in a simple manner.

I am  using a LED strip of WS2812 LEDs (similar to this). Here is what I would like to achieve:

I would like to be able to light  "lets say"  LEDs  1, 3, 5, 7.  Then light LEDs 2, 4, 6, 8  or any other combination of "multiple LEDs", by that I mean maybe LEDs 0, 14, 15, 36, 37, 52, 54.  I am sure you get the idea.

Can I write a single line code to light these LEDs or do I have to write out each line.

Sorry if this is a simplistic question, but I have searched and have not seen anything that may accomplish this, or I just over looked it.

Thanks in advance for your help

I have to say that I do not have any experience with the ws2812 led strip but basically it is used with the Adafruit_Neopixel library where you have the function pixel_obj.setPixelColor(pixel_number,pixel_obj.Color(R,G,B)
and the function pixel_obj.show().
Now you basically want to make the code in void loop() clean and there is a wide choice of possibilities and techniques to use. The simplest is not to do it, but if you want you can write a library to do it or write a function that takes the number of the pins and light 'em up (all with the same color), like this
void light_pixel(int pixels[],int Red,int Green,int Blue){
    for(int i=0;i<NUMPIXELS;++i){
        pixel_obj.setPixelColor(pixels[i],pixel_obj.Color(Red,Green,Blue));
    }
    pixel_obj.show();
}
This works assuming you have declared pixel_obj in the outermost scope, and you will call the function like this:

#include <Adafruit_NeoPixel.h>
#define PIN //Whatever you pin is
#define NUMPIXELS //Thenumber of the pixels in your strip
Adafruit_NeoPixel pixel_obj = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
// You may have to modify the third parameter Rationale: You didn't
// specified anything about your led strip
void setup(){
pixel_obj.begin();
pinMode(PIN, OUTPUT);
}
void light_pixel(int pixels[],int Red, int Green, int Blue){
for(int i=0;i<NUMPIXELS && pixels[I]!=-1 ;++i){
    pixel_obj.setPixelColor(pixels[i],pixel_obj.Color(Red,Green,Blue));
}
pixel_obj.show();
}
void loop(){
int my_pixels[NUMPIXELS]={1,3,5,7,-1}; // Using -1 as terminator
// Initialize the array . Disclaimer: this is not optimised and you might use
// new opearator or better pass the reference of a vector to the function so
// that you can modify the range of the vector and have a more concise function
light_pixel(my_pixels,255,255,255);
delay(1000);
light_pixel(my_pixels,0,0,0);
}

Then you can change the number of my_pixels with a smile array assignment
This function is just a sample to get the job done but I'd recommend you to study further the C/C++ programming language in general in order to write better code
Good Luck!


Arduino Mega pin conflict I am building a rather complicated model railroad crossing signal and have moved to using the Mega since I need more pins than the Uno. Upon reading the specs of the Mega on the Arduino.cc website I noticed a potential pin conflict, or not, maybe they serve a dual purpose?

External Interrupts: 2 (interrupt 0), 3 (interrupt 1), 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2).
I2C: 20 (SDA) and 21 (SCL).

SDA and Interrupt 3 both function on pin 20? Likewise with Interrupt 2 and SCL?
I assume this is true, how/why do they share the same pin?

Lots of things share pins. It's normal. The "how" is that those pins are connected, internally, to multiple bits of the circuitry.

The "why" is simply because if you had a discrete pin for each possible function you would end up with a chip the size of your desk.

Pretty much every single pin on the chip has multiple functions on it.


About Making Library There is a tutorial in the Arduino website on how to create a library. The tutorial gives the following codes for the header:

class Morse
{
  public:
    Morse(int pin);
    void dot();
    void dash();
  private:
    int _pin;
};

My questions are:

What is the purpose of this line: Morse(int pin);
If any, what is the name of this line?

What is the purpose of this line: Morse(int pin);

It is the method that is called when you create an object of class Morse when only passing a single int:

Morse somemorse(1);

  If any, what is the name of this line?

It has multiple names, depending on what aspect you care about:

It is a constructor for the class Morse.
It is a forward declaration for the method Morse::Morse(int).


Why does arduino work on usb power? The arduino website states that the operating voltage of an arduino is 7-12V.

Why does the arduino work powered on just usb then? As usb only outputs 5V and 500ma.

Is it preferable to say run the arduino on an external 9V dc power source, or does it make no difference?

The arduino website states that the operating voltage of an arduino is 7-12V.

That's when it goes through the voltage regulator. It's a linear regulator, meaning it wastes a lot of power as heat. The regulator outputs 5V that's given to the MCU. The USB voltage bypasses the regulator and goes to a fuse before going to the common 5V for the board. If less than 7V is given to the regulator, it will produce less than 5V.

  Is it preferable to say run the arduino on an external 9V dc power source, or does it make no difference?

Usually, yes. A 9V supply would give you more than 500ma, giving you flexibility to add higher current components like motors and lots of LEDs. It will make no difference if you have a single LED connected.


LED Pin 13 Input or Output? It is not clear to me whether Pin 13, corresponding to the LED, should be driven by an external voltage or not.

From the documentation,

  LED: 13. There is a built-in LED driven by digital pin 13. When the
  pin is HIGH value, the LED is on, when the pin is LOW, it's off.

However, in the "Blink" example code I am running, the Pin 13 appears to be driven by the ATmega328:

void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(100);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(2000);              // wait for a second
}

If I now attach a voltage source to Pin 13, will there be contention issues?

Like any other I/O pin, there should be no problem driving this pin (and
thus the builtin LED) from an external source, as long as you make sure
it is in INPUT mode. If the pin is set to OUTPUT you will likely
damage the Arduino.

Warning: If you have the Blink example already loaded in the
Arduino, the pin is in output mode. Be sure to upload another program,
that does not set pin 13 to output, before connecting anything that
could drive pin 13.


Handling serial streams biggers than the available ram I need to parse text coming into my MC (Leonardo) over the hardware serial port. The data comes in burst, and the parsing routine manage the data flow with easy when it is less than the serial buffer.

I will like to be able to receive around 512Kb of serial data, save it somewhere (not in the arduino memory of course) and the execute the parsing routine on it. I think saving the stream to an external EEPROM and then retrieving it slowly so my parsing code can actually fallows will do the trick. I can control the speed of the serial stream from 300 bauds (not optimal) up to 112000 bauds.

Is the approach correct? Can I write to the EEPROM faster than a 9600 bauds serial stream without collapsing the arduino?

You can parse indefinitely large amounts of data with a state machine parser.

General description: State machines

As an example, I wrote recently an HTTP server which parses incoming HTTP data (eg. cookies, parameters, POST data, GET data) on-the-fly.

You need enough RAM for one item of data, naturally. But then you act upon it, and then discard it. In the case of the web server, you could conceivably process a complex form with thousands of actions on it (eg. turn on switch 5, pump 3, heater 22). It parses each action, and then you act on it, then you parse another action.

You can even consider the Arduino bootloader as an example of this. The Optiboot bootloader is 512 bytes on a Uno, but it can re-flash 32 KB of program memory. How? The programming data comes down in bursts (packets, if you like) and it processes each packet at a time, then discards it and reads the next one.


Sleep and Wake Arduino according to LDR interrupt I have to sleep the system in the night and have to wake the system in day time. I am using LDR to get input. LDR input is connected to interrupt pin 0 of Arduino Uno.

Here is my code.

#include <avr/sleep.h>
int led =13;
int triggerPin = 2;

void wakeUpNow()
{

}

void setup()
{
pinMode(triggerPin, INPUT);
pinMode(led, OUTPUT);
attachInterrupt(0, sleepNow, LOW);
}

void loop()
{
digitalWrite(led, HIGH);;
delay(1000);
digitalWrite(led, LOW);
}

void sleepNow()
{
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
attachInterrupt(0,wakeUpNow, RISING);
sleep_mode();
sleep_disable();
detachInterrupt(0);
}

Cannot we attach two function in a interrupt?

Edited
The following code works perfectly. I want to replace the conditional check with interrupt.

#include <avr/sleep.h>
int led =13;
int wakePin = 2;

void wakeUpNow()
{
delay(100);
}

void setup()
{
pinMode(wakePin, INPUT);
pinMode(led, OUTPUT);
//attachInterrupt(0, sleepNow, LOW);
}

void loop()
{
digitalWrite(led, HIGH);;
delay(1000);
digitalWrite(led, LOW);

if(digitalRead(wakePin)==LOW)
  sleepNow();

}

void sleepNow()
{
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
attachInterrupt(0,wakeUpNow, RISING); function
sleep_mode();
sleep_disable();
detachInterrupt(0);
}

I want to replace `

if(digitalRead(wakePin)==LOW)
  sleepNow()

with`

attachInterrupt(0, sleepNow, LOW);

Please let me know how I can do that.

Thank you.

I want to replace the conditional check with interrupt.

Why? If it is awake it might just as well be testing the pin as doing anything else.

If you make it an interrupt, in the ISR interrupts will be off. Then if you go to sleep it will never wake.

So, your current design is the correct one, except:

attachInterrupt(0,wakeUpNow, RISING); function

What is function doing there?


A function-definition is not allowed here before '{' token I'm trying to light up 81 on a 4-digit 7-segment display, but when I try to upload the code to my Uno R3 it gives me this error: "a function-definition is not allowed here before '{' token". I'm new to Arduino and this is my second day using it, so I would like to get help and know how to fix this problem. Here is my code:

int isej1 = 2;
int isej2 = 3;
int vienetas[] = { 12, 11 };
int astuonetas[] = { 13, 12, 11, 10, 9, 8, 7 };

void setup() {
  pinMode (vienetas[2], OUTPUT);
  pinMode (astuonetas[8], OUTPUT);
  pinMode (isej1, OUTPUT);
  pinMode (isej2, OUTPUT);
}

void uz_vien() {
  digitalWrite (vienetas[0], HIGH);
  digitalWrite (vienetas[1], HIGH);
}

void uz_astuon() {
  digitalWrite (astuonetas[0], HIGH);
  digitalWrite (astuonetas[1], HIGH);
  digitalWrite (astuonetas[2], HIGH);
  digitalWrite (astuonetas[3], HIGH);
  digitalWrite (astuonetas[4], HIGH);
  digitalWrite (astuonetas[5], HIGH);
  digitalWrite (astuonetas[6], HIGH);
}

void is_vien() {
  digitalWrite (vienetas[0], LOW);
  digitalWrite (vienetas[1], LOW);
}

void is_astuon() {
  digitalWrite (astuonetas[0], LOW);
  digitalWrite (astuonetas[1], LOW);
  digitalWrite (astuonetas[2], LOW);
  digitalWrite (astuonetas[3], LOW);
  digitalWrite (astuonetas[4], LOW);
  digitalWrite (astuonetas[5], LOW);
  digitalWrite (astuonetas[6], LOW);

void loop() {
  digitalWrite (isej1, LOW);
  digitalWrite (isej2, HIGH);
  void uz_vien();
  delay(5);
  void is_vien();
  digitalWrite (isej1, HIGH);
  digitalWrite (isej2, LOW);
  void uz_astuon();
  delay(5);
  void is_astuon();
}

You are missing a "}" just before loop

  void is_astuon() {
    digitalWrite (astuonetas[0], LOW);
    digitalWrite (astuonetas[1], LOW);
    digitalWrite (astuonetas[2], LOW);
    digitalWrite (astuonetas[3], LOW);
    digitalWrite (astuonetas[4], LOW);
    digitalWrite (astuonetas[5], LOW);
    digitalWrite (astuonetas[6], LOW);
   } // <- missing here.
  void loop() {


Button and twist knob to send keystroke to PC As a novice, I would like to create a small breadboard with 5 items on it. 3 toggle buttons, and two constant spin (ie. no stop at 360 degrees) knobs.
Is then like the bottoms to send what ever key stroke (single key pee click) to the pc as if it was from a keyboard (maybe even a shift+key?)
And the knobs send keystrokes too. On each “click” as I don’t want smooth knobs. Ones that kinda of click per degree. Not sure how to explain that.
It’s for Flight Simulator. Doing it with a mouse, from distance, with small buttons is challenging. And twisting knobs with the mouse in bumpy conditions is even worse.
So planning on using my Nana, connected to a USB port for
Power and signal.
Can anyone guide me in the right direction? Would I need 3rd party software to convert signals to keystrokes on the pc?
I think there is a keyboard library - but from what I read, it takes over your keyboard. That is, once the Arduino is connected and listening - the main keyboard no longer functions. Is that a misunderstanding? I need both to be operational.
I’m guessing something like this as it has “positions”.
https://www.ebay.com.au/itm/Rotary-Encoder-Module-Arduino-Compatible/232624628710?hash=item36298223e6:g:JIIAAOSwg31aVFVW

As a novice, I would like to create a small breadboard with 5 items on it. 3 toggle buttons, and two constant spin (ie. no stop at 360 degrees) knobs.

Those knobs are called "Rotary Encoders".

Is then like the bottoms to send what ever key stroke (single key pee click) to the pc as if it was from a keyboard (maybe even a shift+key?)

Then you really want an Arduino with a "native" USB connection, like the Leonardo or Micro.

Can anyone guide me in the right direction? Would I need 3rd party software to convert signals to keystrokes on the pc?

Not with a Micro or Leonardo - you just use the Keyboard.h library.  If you want to use your Nano then yes, you can only talk serial, and you will have to have some third party software that interprets serial commands and injects keyboard signals into your OS.  I think there's some Python projects around that do that kind of thing. Or there is "professional" software, like 232key that can do it for you.


How to keep a 24 hour maximum and minimum temperature I am keeping a simple weather station to monitor humidity and temperature in my greenhouse. I have a ds18b20 and dht probes.  everything works great and I even used a little trick to hold my maximum and minimum values, but I would like them to reset every 24 hours. Is there anyway i can code the arduino to reset itself. i tried several examples of connecting digital pins to the reset pin and i couldn't get any of those to work.  i tried to reset the values of my max and min to 0 and 99 respectively after my millis() reached the equivalent of a day, but they just stuck at 0 and 999. I understand fully why it does this i just don't know how to fix it. all i want to do is reset my minimum and maximum temperatures after 24 hours.

//       Green HAUS Version 1 by Kent Scipione 9/3/2017
//       Monitors temperature and humidity
long timenow;
long day = 86400000; // 86400000 milliseconds in a day
long hour = 3600000; // 3600000 milliseconds in an hour
long minute = 60000; // 60000 milliseconds in a minute
long second =  1000; // 1000 milliseconds in a second

#include <OneWire.h>
#include <DallasTemperature.h>
#include <SPI.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 4
#define ONE_WIRE_BUS 10
double temp;  // sensor is precise to .1 degree.
//Double gives smoother serial graph, byte doesn't overflow oled screen
Adafruit_SSD1306 display(OLED_RESET);
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

#include <Adafruit_Sensor.h>
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

int maxtemp=0;
int mintemp=999;

void setup() {

  Serial.begin(9600);
  Serial.println("green HAUS Version 1 by Kent Scipione 9/3/2017");
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.display();
  display.setTextColor(WHITE);
  sensors.begin();
  dht.begin();

}

void loop() {
  timenow = millis();
  sensors.requestTemperatures();
  temp = sensors.getTempFByIndex(0);
  int humid = dht.readHumidity();
  float dtemp = dht.readTemperature(true);
  if (temp > maxtemp) {
    maxtemp=temp; }
  if (temp < mintemp) {
    mintemp=temp; }

  if (timenow >= day){
      digitalWrite(4, HIGH);
      pinMode(4, OUTPUT);       //*************************this is the part where I'm trying to reset the mintemp and maxtemp**********

    }

  Serial.print("Probe Temperature: ");
  Serial.println(temp); Serial.println("*F");
  display.setCursor(0,0);  //refreshes display
  display.clearDisplay();
  display.setTextSize(1); display.print("Probe "); display.println(temp);  //line 1 of text
  display.print("DHT  "); display.print(dtemp); display.print("  "); display.print(humid); display.println(" %");  //line 2 of text
  display.print("HIGH "); display.println(maxtemp);           //line 3 of text
  display.print("LOW  "); display.println(mintemp);   //line 4 of text
  display.display();

}

Thank you so much for your help this is driving me mad haha

You should also keep a timestamp of the last time you reset the min and max otherwise the arduino will keep thinking it's a new day:

//add to globals
unsigned long lastDay = 0;

and inside loop()

  if (timenow-lastday >= day){

      maxtemp=0;
      mintemp=999;
      lastDay = timenow;
  }


Arduino Command Line Interface - How to change boardsmanager.additional.urls I am building a Travis CI job to test my Arduino Library and it needs to install external board definitions.

Is there a way that I can set the boardsmanager.additional.urls from the command prompt like it would have been done in the Preferences window?

Or should I create preferences.txt file? (If so where does that live in a Linux environment)

Found the solution:

arduino --pref "boardsmanager.additional.urls=http://arduino.esp8266.com/stable/package_esp8266com_index.json"


Function pointer or abstract class? I need to implement callback in my C++ library. The "proper" C++ way of doing it would be to create an interface (or pure abstract class) and pass it to interested party. I'm wondering though, would that be optimal?

My analysis:

Function pointer - occupies 2 bytes in memory (+code of function)
Class derived from abstract one - occupies 2 bytes in memory PLUS 2 bytes for VMT (since we have derived method) PLUS size of VMT table (if any) (+code of method).

Is optimizer smart enough to compile abstract class with single method as method pointer? Which solution is more optimal in regard of memory and speed? Is my analysis correct?

Sometimes you want your callback to be fed some data that you provide
when you register that callback. Here is a very common callback pattern
in plain C that does that:

// The API:

typedef void (*callback_t)(void *data);
void register_callback(callback_t callback, void* data);

// Usage:

typedef struct {
    // stuff only the user of the API knows about.
} my_data_t;

void my_callback(void *in_data)
{
    my_data_t *data = (my_data_t *) in_data;
    // do something with data->foo, data->bar...
}

// ...somewhere else:
my_data_t my_data = { stuff... };
register_callback(my_callback, (void *)&my_data);

The problem is: it's clumsy. C++ classes allow you to pack together the
code (the callback function) and the data it needs. Thus, if in your use
case you need to pass data to the callback, by all means use a C++
class. It will make your life easier and you are unlikely to even notice
the memory overhead.

However, if you only need to pass a function, with no attached data,
then a plain function pointer would be both easier for the API user and
optimal memory-wise.


For which type of serial communication is Arduino Severino designed? Arduino has become quite costly where I come from (2/3 of the price of Raspberry PI) so I have created an Arduino Severino clone.

I had used the device with the RS-232 Usb-Serial converter. But after a (long) while, the device stopped working. My friend came up with a point that RS-232 communication ranges between +6 to -6 V (with thresholds at +3 and -3 volts).

So I have tried FT232 which uses 0 to 5 volts instead. I have a little Chinese FTDI chip designed to do that:

However, after connecting it, it behaves unexpectedly. (it had crashed my PC, one of the communication LEDs is on all the time...) I realised that the Arduino board might get broken for a different reason (an accidental short-circuit is very likely).

So for which type of communication is this "Arduino" designed?

Looking at the schematic of that board it uses a very crude signal inversion for the RS-232.  This allows it to work of a standard RS-232 signal direct from a computer - just.

It's far from ideal and really should use a MAX232 (or similar) chip for the interface.

Your FT232 adaptor should bypass that chunk of the circuit and connect direct to pins 0 and 1 of the Arduino clone.  The DTR pin of the FT232 should connect to the RESET pin of the Arduino clone via a 100nF capacitor to allow the IDE to reset the board to enter the bootloader.  Oh, and of course, connect the ground to your Arduino clone too (something Arduino users often forget).

You can follow the serial breakout board portion of the Arduino breadboard tutorial and apply it to your board.


Hardware interrupts for buttons not directly assigned to pins The Adafruit LCD shield offers an LCD and access to 4 button, using only a two wire connection with the Arduino.
This is achieved with the MCP23017 I2C port expander IC.

These buttons are not directly assigned to pins, since only two pins are required for the whole communication, via the I2C protocol.

Can i use a hardware interrupt with any of the 4 buttons?
If not, is there any workaround to trigger an interrupt when one of these buttons is pressed?

PS: I am using Arduino Due

The MCP23017 has two interrupt outputs. The Adafruit shield however doesn't bring out either of those two pins. You could solder a wire between one of these pins and one of the unused arduino-header pins.


Converting a char* with numbers to a double is giving me 0.0 in return I recently made a thread where I read BLE data that has three different numbers/values. The data changes but it typically looks something like this:
0,5 -0,1 0

I successfully store the three numbers in a unique char* but when I try to convert the char* to a double I get the value 0.0 in return.

This is my code:

        while (tok)
        {
            if (currentRow == 0)
            {
              currentRow = currentRow +1;
              double a = atof(tok);
              Serial.println (a);
            }

            else if (currentRow == 1)
            {
              currentRow = currentRow+1;
              double b = strtod(tok, NULL);
              Serial.println (b);
            }

            else {
              currentRow = 0;
              double c = atof (tok);
              Serial.println (c);
            }

            tok = strtok(NULL, " ");
        }

The value that was being sent used a comma "," instead of a dot "." that was needed in order to convert the number.


Arduino while loop with or condition How do I write a program to wait (delay) until one out of two buttons pressed? I have written a program to wait until a single button is pressed. It's working fine. However, if I extend it to second button it's not working. Pls help on this.

while (digitalRead(bt_Select) == HIGH) {} -- working.
while (digitalRead(bt_Select) == HIGH || digitalRead(bt_Reject) == HIGH) {} -- Not working.

Complete code:
const int bt_Select = 2;
const int bt_Reject = 3;

void setup() {
  Serial.begin(9600);
  pinMode(bt_Select, INPUT_PULLUP);
  pinMode(bt_Reject, INPUT_PULLUP);
}

void loop() {
  Serial.println("Pl input:");

  while (digitalRead(bt_Select) == HIGH {} // This is the line I change

  if (digitalRead(bt_Select) == LOW) {
    Serial.println("Select Button pressed:");
    delay(250);
    Serial.println("");
  }

  if (digitalRead(bt_Reject) == LOW) {
    Serial.println("Reject Button pressed:");
    delay(250);
    Serial.println("");
  }
}

while (digitalRead(bt_Select)==HIGH||digitalRead(bt_Reject)==HIGH){}
should be
while (digitalRead(bt_Select)==HIGH&&digitalRead(bt_Reject)==HIGH){}
The first loop would break only if you press both buttons at once. I believe you are trying to break if either button is pressed.


Using Arduino UNO to retrieve ATMega328P-PU chip signature Good day.

I have successfully built and tested an Arduino-on-breadboard about 2 days ago.

The device is rather straight forward, I have added a voltage divider and an LED to indicate power.

The schematics are as follows:

And this is a picture of the actual board:

I am using an ATMega328P-PU as a Microcontroller chip.

I uploaded quite a few sketches on the board and all seemed to work well. I was trying to upload a sketch yesterday but I got:
 "avrdude: Yikes! invalid device signature".

I rebooted the computer, rebuilt the entire board again, and tried once again to load a sketch using Arduino as ISP. The message changed again to:

avrdude: Expected signature for ATmega328P is 1E 95 0F
         Double check chip, or use -F to override this check.
Wrong microcontroller found.  Did you select the right board from the Tools > Board menu?

I did a search online and I have found many forums suggesting that I change the avrdude.conf file parameters to different signatures "Although these are mainly targeted at people using ATMega328-PU, not ATMega328P-PU" but this also did not help.

I tried burning the bootloader again but I still get the same error message.

I tried to find a way to "retrieve" the chip signature, but I didn't.

I know that there is a chance that I have bricked the chip somehow, but how do I know for sure? and is there anyway that one can use and Arduino as a tool to retrieve the chip signature or verify if the chip itself is dead?

Thank You

There is a nice explanation here about Atmel chip signatures.

It sounds like you already know this, so for others looking for help:

It says that there are different signatures in the Atmel chips you mention.  That you can over ride the Avrdude program using an "-F" switch.  Or you can change the Avrdude configurations to use the "other" Atmel chip (however, the consequences if any were unknown by the author).

This may be an obvious step, but double check to make sure the IDE's target board settings are correct.

You may also want to check the communications between the programmer and the target.  You might look into dropping the speed.  But the better way is to scope the lines to see if data is being sent to the target and if the target is talking back.  From that you can infer if the problems is a bad connection or if the chip has been damaged.

If you want to dig further using software tools you could look into driving Avrdude for your self.  There is a easy to read tutorial here and what appears to be an everything you wanted to know and more document here.

In the 1st tutorial (from ladyada.net) we see a test which they purposely try the wrong signature:

  Just for kicks try running this command avrdude -c usbtiny -p atmega8
  -U flash:w:test_leds.hex

  You'll see that it stops at step 2, once the signature is different
  than the expected one it stops. This is because code that is compiled
  for an attiny2313 wont run on an atmega8 (this is true of most
  microcontrollers, the .hex files are not cross compatible)

But more interestingly, Avrdude prints out the signature read back from the target!  So, if you run the same test, you could tell if Avrdude is able to communicate at all with the target.  That is, you may see all zeros or all ones or even an alternate message from Avrdude. Which could be an indication that the target is not talking.


Connect one HC-05 "master" to two slaves at the same time Does any one know what AT+CMODE=2 "slave loop" used for. As I try to connect one HC-05 master to two slaves using it, but it didn't work.
i donot know if AT+cmode=2 is used for connecting to multiple slaves or not as i want to know what is used for , i tried to understand what it do from the HC-05 datasheet but i didnot find anything useful about it excpet for what is this image

AT+CMODEis mainly used for setting the address pairing purpose. What chrisl stated is exactly true, you cannot connect more than 1 slave to the master at a time. When you set the parameter as 2 you actually set a passive connection, a connection between master and slave to receive the remote Bluetooth master device data and send it back to the master device. It is like a feedback-loop, and is mainly related for testing the connectivity and other features of the PAN (Personal Area Network). So actually whatever is received from the master, is sent back again to the master by the slave.


How can the sensitivity of capacitive touch sensors be limited? I have an Adafruit circuit playground classic, and the touch-pads are so very sensitive. From a centimeter away, they trigger.  I would be happy to just have regular inputs, or to have the sensitivity reduced. How can I do this?

To clarify, here is my code:

//keyboard control for TuxKart power Glove
#include <Adafruit_CircuitPlayground.h>
#include <Keyboard.h>
#include <Mouse.h>
// set pin numbers for the five buttons:
const int Fire = 6;
const int Nitro = 9;
const int Eagle = 10;
const int _Esc = 12;

bool slideSwitch;

void setup() { // initialize the buttons' inputs:
  pinMode(Fire, INPUT_PULLUP);
  pinMode(Nitro, INPUT_PULLUP);
  pinMode(Eagle, INPUT_PULLUP);
  pinMode(_Esc, INPUT_PULLUP);

  Serial.begin(9600);
  // initialize mouse control:
  //Mouse.begin();
  Keyboard.begin();
}

void loop() {
  if (!CircuitPlayground.slideSwitch()) {
    return;
  }

  // use the pushbuttons to control the keyboard:
  if (!digitalRead(Fire) == HIGH) {
    Keyboard.write('KEY_SPACE');
    Serial.println("F");
  }
  if (!digitalRead(Nitro) == HIGH) {
    Keyboard.write('n');
    Serial.println("U");
  }
  if (!digitalRead(Eagle) == HIGH) {
    Keyboard.write(0xB2);
    Serial.println("N");
  }
  if (!digitalRead(_Esc) == HIGH) {
    Keyboard.write(0xB1);
    Serial.println("K");
  }
delay(200);
}

This code or any other, where capacitive touch sensitivity has not been specified, yields pins having extreme sensitivity. I have read the comments, that say the MCU doesn't feature this natively. If that were true, how would the pins remain sensitive?

My solution to this is to set sensitivity so low, that it is negligible. If capacitive touch sensing is not specified, why am I getting that functionality? Why would this code give me capacitive touch sensing?
Ideally, I would disable the touch sensing somehow, or have the pins simply behave normally, like any other Arduino based device that doesn't have touch sense. But what I have guessed, (shown in code) doesn't work. If there is a more explicit way to specify that IO pins should act as normal pins, without capacitive touch sensing, I would surely like to know.

digitalRead(pin) is the wrong way to read capacitive touch inputs.

In the file from the example you linked in your answer, the reading is made by calling CircuitPlayground.readCap(pin, num_samples) and then the returning value is compared to a threshold.

const uint16_t TOUCH_THRESHOLD = 300;

...

if (CircuitPlayground.readCap(Fire) >= TOUCH_THRESHOLD) {
   Keyboard.write(KEY_SPACE);
   Serial.println('F');
}
...

You can change the sensitivity by changing TOUCH_THRESHOLD. You could also add and fiddle with the second argument to change the number of samples.


Powering a MKR with regulated 3.3v I've a low power consumption regulator to get 3.3V from two 1.5V batteries.
I'm going to use it for powering an arduino MKR (MKRFOX1200), so my question is where I should connect it, to the battery connector or directly to VCC.

Looking at schematics it's not clear to me which is the best option in terms of power saving, as VCC seems better but I don't know if it's ok to use that pin to give power

You don't really need your regulator. That board has a connection (X1) intended for directly connecting two AA batteries (according to the schematic).

However, if you want to keep it regulated at 3.3V for other reasons (the MCU will happily run from as low as about 1.62V) then sure - use your regulator.  But just treat it like batteries regardless. Connect the output of your 3.3V regulator to the battery connector, which goes via the power switching and control circuitry to the 3.3V rail of the board.


DHT11 is not reading Temperature and Humidity when Arduino is powered on using DC power Supply (12V) I am facing one problem. I have code which read temperature and humidity using DHT11 sensor. I uploaded following code using Arduino via USB serial, I can read values of temp, humidity. Values are being read as long as Arduino is connected to same laptop via USB.

TEMPERATURE AND HUMIDITY are being read as 0 when I power on Arduino using DC12v, 700MA adapter.

I want to deploy Arduino with DHT sensors connected with it in Greenhouse to read greenhouse environmental condition but when I power on using DC adapter or battery, it is giving "0" output.

PLEASE HELP TO SOLVE THIS PROBLEM.

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

You haven't really provided enough information to answer. What are you reading the temperatures with. You code just assigns a variable to the readings but does not output that to anything.

I would suggest reading along with this tutorial, for example, and trying out the code they provide: http://www.circuitbasics.com/how-to-set-up-the-dht11-humidity-sensor-on-an-arduino/


Arduino nano as HID Keyboard I'm a bit of a noob in the Arduino area but I found an Arduino nano I bought a long time ago sitting on my shelf and collecting dust,
so I taught "why not make a project". I game a lot of racing games so I wanted to make a simple ignition button with it, but every time I tried to compile or verify it, it says

  Keyboard not found. Does your sketch include the line #include "Keyboard.h"

Get yourself a Arduino Leonardo, Micro or Pro Micro (or Due, Zero, M0). Those can emulate a keyboard.
Start with reading the Arduino Keyboard Mouse reference.

The Arduino Nano can not use the Arduino Keyboard Mouse library.

Since many years, there is a library called "V-USB" that requires some extra hardware and makes it possible for a ATmega328p microcontroller to act as an USB device. It is not something for a beginner.

A few years ago, Arduino has changed the way the USB is used. The NicoHood HID library makes use of the new possibilities. It makes it possible for example to have extended features for a USB keyboard, like the media keys.

For a normal keyboard and mouse, the Arduino Keyboard Mouse library will do. It will be perfect for a ignition button. But you have to buy one of those boards (Leonardo, and so on).


Arduino Ethernet Shield vendor is null I bought Ethernet Shield for Arduino Uno! from AliExpress. It is good work but I scanned my network with Fing and device Vendor name is null.

Can I change/set device Vendor?

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

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

void setup()
{
  Ethernet.begin(mac, ip);
}

The vendor name is not stored on the device, rather it is indicated only by the first three octets or OUI part of the MAC address which is either stored on the device, or in your case set up by software.  Turning this back into a name on another computer which sees its traffic is done by the help of a local or network-sourced OUI lookup table.

Apparently the table your computer is consulting doesn't have an entry for the OUI 0xDE, 0xAD, 0xBE.

And that's not surprising as this is clearly a dummy value put in as a placeholder - read all 6 octets as if they were a word and you'll see it says "dead beef feed" - a variation on a classic magic "illegal" value.

Technically, this is actually a legal value for use on a local network as the 2's bit of the leading octet is turned on, indicating that it is a "locally administered" address, rather than one guaranteed to be unique in all the world as you would expect a proper piece of network hardware to have.

If you find the table your computer is doing OUI lookups in, you could add a DE:AD:BE entry to it.


How can I power a servo and Arduino from the same power supply? I have an ESP8266 NodeMCU which I'm using for an automatic blinds project. The NodeMCU struggles to power the servo on its own, so at the moment I am using a 5 V supply for the servo and a USB cable for the NodeMCU (with a common ground).

The servo is an inexpensive MG996R which is rated up to 7.2 V I've read that NodeMCU can take 5-10 V on the VIN pin.

After I'm done prototyping, I want to only use one power supply. What could I use? Ideally it would be something with just a wall adapter and then I can cut the other and connect that to servo and MCU.

Wire the +5 and Ground from the supply to both the ESP's Vin & Ground and the servo's Vin & Ground. The only thing you have to avoid is trying to power the servo through the ESP.


String use in arduino IDE (this question for understanding) I'm using arduino several month now, And i don't understand when i can use the arduino object of String. I'll explain, I read a lot and the it's look like that this object is a good way to read/write and use strings, But everywhere they say that this object take a lot of RAM. So i made some project, And almost in all of them the String object not work as i expected. When i check the RAM in my projects i see that when my usage of RAM is greater then 65% the string object start to do problems. Because of this i stop use the string object and use only char arrays.

So my question is:

How can i know when i can use String from the beginning?
there is a way to change from char array to string or vase versa easily (i know this is completely different logic)?
How can i avoid the memory problems with the String object?

All this questions come from that the String object is very effective and easy to use and i want to use it, But i'm fear from RAM problems so i'm not using it.

Thank you very much for reading all this, Hope you can help me!

String objects are simple to use. There is a trade-off for simplicity. Strings work by using dynamic memory allocation. Something like this for example:

String foo;
...
foo += 'a';

By adding one character to a string the class has to allocate new memory for the slightly longer string. If you keep doing this you get memory fragmentation.

You are probably better off deciding what your maximum size string is and making that a static array of characters.

So should I use the String objects?

For occasional use they are fine (for example, holding the name of something). They tend to fall down once you start with a small String and keep adding to it, because the code has to dynamically allocate memory, allocating (say) 5 bytes, then 6 bytes, then 7 bytes, and in the process freeing up the original 5 bytes, then 6 bytes and so on. This allocating/freeing process can leave holes in the "heap" causing a thing known as memory fragmentation.

Done to excess you can run out of memory. That is, you might need 100 bytes but have 10 lots of 10 bytes free, with stuff in-between that isn't free.

You don't have lots of memory to start with, so it is probably better, faster and more efficient to decide the largest amount you need for some string, and just make that a character array.


Why does current flow along a wire instead of a resistor right next to it? I am having trouble understanding exactly what is going on in a circuit where when a button is pressed an LED goes on. Also, I have the Arduino UNO.

The schematic can be seen at:

2:36 of this video: Arduino Tutorials: Control a LED with a Button.

So, the part that I don’t understand is, how come when the button is clicked and the current can pass through, the current doesn’t go through the pull down resistor and instead goes along the input wire?

I’m a beginner but do understand concepts like voltage, amps, resistors, Ohm’s law, etc. So answers don’t have to be super simple, but simple enough that I can understand them. Thanks!

So, the part that I don’t understand is, how come when the button is clicked and the current can pass through, the current doesn’t go through the pull down resistor and instead goes along the input wire?

Simple: It does go through the pull down resistor. But  it also goes down the "input" wire.

For simplicity you can imagine that the input is simply a very large resistor. Say, 1MΩ.

The circuit can then be simplified as:

simulate this circuit – Schematic created using CircuitLab

Contrary to popular belief, current does not take the path of least resistance. It takes all possible paths. The quantity of current through each path is proportional to the resistance of the paths.

In this example we have two paths - one with 10kΩ and one with 1MΩ.  That's a ratio of 1:100, and the current will be split accordingly.

You can calculate the current that flows through each resistor simple using Ohm's Law because the wires and switch are (in an ideal world) just not there. The 5V is directly connected across each of the resistors.

So for the 10kΩ resistor the current through is is:

     V      5
I = --- = ----- = 0.0005 = 500µA
     R    10000

And for the 1MΩ it is of course 100x smaller (I'll let you do the maths for that if you want to check), so 5µA.

The full current that the circuit takes is 505µA, with it split between the two resistors.

With the Arduino instead of the 1MΩ resistor it's exactly the same (though the current values may vary somewhat).  500µA flows through the 10kΩ resistor, and "some tiny current" flows through the Arduino.

However, with all that said, the Arduino really doesn't care about the current. All it cares about is the voltage. With the button pressed both the input and the 10kΩ resistor are connected directly to the 5V supply - so the Arduino reads that as "HIGH". When you release the button the input is now connected to ground through the 10kΩ resistor, but there's no current to flow, so there's no voltage across the resistor (the voltage across a resistor is proportional to the current flowing through the resistor - Ohm's Law), so it's as if the input is connected directly to ground - and the Arduino reads that as "LOW".

To be more technically accurate the input of the Arduino is actually more akin to a tiny capacitor.  When you apply 5V to the input it charges that capacitor up. Once it reaches 60% of 5V the Arduino recognises it as a "HIGH" signal.

When you release the button that capacitor is then connected to ground through the resistor, and it discharges through that resistor. Once it drops to 30% of 5V the Arduino sees it as being "LOW".

If you don't have the pull-down resistor, when you remove the 5V from the input that capacitor is still charged. So the Arduino still sees it as a HIGH. The charge in the capacitor will slowly bleed away until it's low enough to be seen as low.

But, (and it's a big but), the capacitor is very sensitive and can be charged up again by ambient energy around the place (radio waves, static electricity, etc). It can harvest enough energy from the environment to get back up to the 60% of 5V and be seen as "HIGH" again. This is known as "Floating", and is something you do not want in your circuit. The input "flaps around" between HIGH and LOW with no control.  Which is why the pull-down resistor is absolutely essential.


qsort is not really sorting I'm working with Arduino and getting some strange errors. qsorting is not sorting correctly.

//using this libraries
#include <ESP8266WiFi.h>
#include <inttypes.h>

//the red struct is

typedef struct {
    int32_t rssi;
    int id;
} red;

//Here is my compare function
int compare (const void * a, const void * b)
{
  yield();
  red *redA = (red *)a;
  red *redB = (red *)b;
  //Serial.printf("redA->rssi: %d, redB->rssi: %d\n",redA->rssi,redB->rssi);
  //Serial.flush();

  return redA->rssi > redB->rssi ? 1 : (redB->rssi < redA->rssi ? -1 : 0);
  //return ( redB->rssi - redA->rssi );
}

void showNetworks(){
  int n = WiFi.scanNetworks(false,false);
  red listOfRedes[n];

  for (int i = 0; i < n; i++) // ...initialize it
  {
    yield();
    listOfRedes[i].rssi = WiFi.RSSI(i);
    listOfRedes[i].id = i;
    Serial.printf("%d: RSSI%d\n", i, listOfRedes[i].rssi);
    Serial.flush();
  }
  Serial.printf("salio\n");
  Serial.flush();
  qsort (listOfRedes, n, sizeof(red), compare);
  Serial.printf("ordeno\n");
  for (int i = 0; i < n; i++) // ...initialize it
  {
    yield();
    Serial.printf("%d: RSSI:%" PRId32 "\n", listOfRedes[i].id, listOfRedes[i].rssi);
  }
}

and this is the output i get

0: RSSI-69
1: RSSI-65
2: RSSI-72
3: RSSI-50
4: RSSI-60
5: RSSI-87
6: RSSI-87
7: RSSI-79
8: RSSI-80
9: RSSI-88
10: RSSI-74
11: RSSI-77
12: RSSI-78
13: RSSI-83
14: RSSI-79
15: RSSI-60
16: RSSI-85
17: RSSI-86
18: RSSI-66
19: RSSI-88
20: RSSI-80
21: RSSI-74
22: RSSI-81
23: RSSI-87
salio
ordeno
4: RSSI:-60
1: RSSI:-65
0: RSSI:-69
3: RSSI:-50
18: RSSI:-66
15: RSSI:-60
2: RSSI:-72
10: RSSI:-74
11: RSSI:-77
21: RSSI:-74
19: RSSI:-88
20: RSSI:-80
22: RSSI:-81
23: RSSI:-87
12: RSSI:-78
5: RSSI:-87
6: RSSI:-87
7: RSSI:-79
8: RSSI:-80
9: RSSI:-88
13: RSSI:-83
14: RSSI:-79
16: RSSI:-85
17: RSSI:-86

As you can see the sorting is not OK and I don't get why.
Thank you in advance and sorry for my poor English.

In your program there is this line of code:

  return redA->rssi > redB->rssi ? 1 : (redB->rssi < redA->rssi ? -1 : 0);

Which appears to return a 1 if A is greater then B other wise it will return a 0.  This code can not tell the difference between A < B and A == B.  Consider altering this line of code to allow returning 1 for A > B, 0 for A == B and -1 for A < B:

  return redA->rssi > redB->rssi ? 1 : (redA->rssi < redB->rssi ? -1 : 0);


Change the sequence of LEDs with button press I am new to arduino.
I have created a circuit , here is the image:

I want something that as I press the button the sequence of LEDs will change and as I press the button again , the sequence will change again.

I programmed code as following but it don't works correctly:

int led1 = 11;
int led2 = 10;

int output = 2;
int input = 4;
int mode = 0;

void setup() {
  pinMode(led1,OUTPUT);
  pinMode(led2,OUTPUT);
  pinMode(output,OUTPUT);
  pinMode(input,INPUT_PULLUP);
  digitalWrite(output,LOW);

}

void loop() {
  while(mode == 0 && digitalRead(input) == 1){
    digitalWrite(led1,HIGH);
    digitalWrite(led2,HIGH);
    delay(100);
    digitalWrite(led1,LOW);
    delay(100);
    digitalWrite(led1,HIGH);
    delay(100);
    digitalWrite(led2,LOW);
    delay(100);
    digitalWrite(led2,HIGH);
  }
  if(digitalRead(output) == 0){
    mode++;
    if(mode >= 2){mode = 0;}
  }
  while(mode == 1 && digitalRead(input) == 1){
    analogWrite(led1,255);
    delay(400);
    analogWrite(led1,150);
    delay(400);
    analogWrite(led2,255);
    delay(400);
    analogWrite(led2,150);
  }

}

According to the above code , two leds led1 and led2 are connected with arduino. When the button is off the both LEDs turns on then led1 turns off then turn on again , next time led2 turns off and turns on again.As the button will be pressed , brightness of led1 will be less than the brightness of led2 and then
will again be equal to the brightness of led2, then brightness of led2 will be less than the brightness of led1 and then will be equal to the brightness of led1. But as I press the button , nothing happens but the led1 and led2 keeps turning on and off . However sometimes when I press the button then it works.

What is the problem with my code and how to solve it?

There are a few issues with your wiring.

As already stated in comments, you should not connect the battery to
the 5V input of the Arduino. Use the “Vin” input instead.
You should put a current-limiting resistor in series with each of your
LEDs. Any value in the range 330 Ω – 1 kΩ should be fine.
Your Arduino (and your LEDs) will last longer if you stop abusing it!
There is no point in using two digital IO pins to read a button. Just
connect the button between a digital input and GND. Alternatively, you
can wire it like in Holmez's answer, but that requires an extra wire
and a resistor.

And there are two main issues with your code:

You forgot to debounce the button. Mechanical button are bouncy.
The easiest way to debounce them is to use a ready-made library like,
e.g., Bounce2.
You are using delay(), which means you cannot respond to user input
while your Arduino is busy delaying. You should manage your timings
with milis() instead, as explained in the Blink Without Delay
Arduino tutorial.

Here is my take at your problem. This is based on the
finite state machine programming pattern, with a state defined by
two variables. There is a mode variable used to keep track of whether
we are in “digital” or in “analog” mode. And there is a “phase” variable
used to keep track of the phase along the blinking pattern. Phases 0
through 3 correspond to (LED1/LED2) in the states: (HIGH/HIGH),
(LOW/HIGH), (HIGH/HIGH), (HIGH/LOW). Note that, for simplicity, the LEDs
are controlled with analogWrite(), even in “digital” mode.

#include <Bounce2.h>

const uint8_t BUTTON_PIN = 4;
const uint8_t LED1 = 11;
const uint8_t LED2 = 10;

Bounce button;

void setup()
{
    button.attach(BUTTON_PIN, INPUT_PULLUP);
    pinMode(LED1, OUTPUT);
    pinMode(LED2, OUTPUT);
    analogWrite(LED1, 255);
    analogWrite(LED2, 255);
}

/*
 * Vary the LED brightnesses along the following pattern:
 *
 *  phase:   0   1   2   3   0
 *          ___     ___________
 *  LED1:      \___/
 *          ___________     ___
 *  LED2:              \___/
 */
void loop()
{
    static enum { DIGITAL, ANALOG } mode = DIGITAL;
    static uint8_t phase = 0;
    static uint16_t phase_duration = 100;
    static uint8_t low_level = 0;
    static uint16_t last_change = 0;

    // Switch modes on button presses.
    button.update();
    if (button.fell()) {
        switch (mode) {
            case DIGITAL:
                mode = ANALOG;
                low_level = 150;
                phase_duration = 400;
                break;
            case ANALOG:
                mode = DIGITAL;
                low_level = 0;
                phase_duration = 100;
                break;
        }

        // Set initial phase.
        phase = 0;
        last_change = millis();
        analogWrite(LED1, 255);
        analogWrite(LED2, 255);
    }

    // Switch phase after phase_duration elapsed.
    if (millis() - last_change >= phase_duration) {
        last_change += phase_duration;
        phase = (phase + 1) % 4;
        switch (phase) {
            case 0:
                analogWrite(LED2, 255);
                break;
            case 1:
                analogWrite(LED1, low_level);
                break;
            case 2:
                analogWrite(LED1, 255);
                break;
            case 3:
                analogWrite(LED2, low_level);
                break;
        }
    }
}


Use an L293D with Arduino I am making a 2-wheeled Arduino car controlled by T.V. remote for a science fair tomorrow. I have found a tutorial for the IR part. I brought this  L293D motor driver to control a 2-wheeled car. I am facing a problem. I know where to connect the motors (because there are indications stating M1 and M2) but I don't know where to connect the motor driver to the Arduino and to the batteries.

I checked over the net but couldn't find any tutorial for this kind of board. Also I have no experience in all this so I don't want to risk it. I don't want any code or anything, just where to connect what.

Any help is appreciated.

All the inputs are clearly marked.

The battery connects to +12V and GND
The Arduino's 5V and GND connect to 5V and GND.

The control signals connect to the header of control signals. ENx is the PWM signal for the speed for motor X. IN1/IN2 are the direction/brake controls for motor 1, and IN3/IN4 are the direction/brake controls for motor 2.

The signal labels are exactly the same as the pin names for the chip and match up precisely with every single tutorial on the net for using the L293D with the Arduino.


Can send AT+ commands, but can't upload sketch to ESP8266 via Arduino Uno Connected a generic ESP8266 to an Arduino Uno.

I can send AT commands fine and generate a normal response, but cannot upload sketches to the ESP8266. I have "Generic ESP8266 Module selected as the board. Tried everything e.g. switching Tx and Rx, connecting GPIO0 and GPIO2 to to Vcc or ground, but to no avail.

Arduino IDE spits this out -

esptool v0.4.5 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to ck
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    stat C:\Users\Michael\AppData\Local\Temp\build7227402767538495982.tmp/wifi_setup.cpp.bin success
    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 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
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 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
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 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
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 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
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 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
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 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed

You mention:

  connecting GPIO0 and GPIO2 to to Vcc or ground

I've had success with this sequence:

GPIO0 to gnd (and hold momentarily)
RST to gnd (then let go, while holding GPIO0 to gnd)
let go of GPIO0 from gnd (e.g. let it float again)

To do a firmware flashing, you need to hold GPIO0 to ground for the duration of the flashing process, so the sequence would be slightly different.

You can do this just prior to "build and upload" in the Arduino IDE—provided the build process doesn't take too long.  It will sometimes still fail, in which case reset the ESP8266 (RST to gnd momentarily) and restart the sequence.

I've found a little test/development harness (like this one http://www.buildcircuit.com.au/esp8266-test-board) is very handy for doing this repeatedly.


Arduino sketch does not repeat I have a Problem with my code.

My Goal is to receive a Ethernet message via UDP and send the message back via CAN.

It works fine but only with the first packet I send. When I send the same packet again there is no Response as you can see in the screenshot.
I´m using the Arduino Due with a Transceiver. The Programm which sends and reads the Messages is Vector Canoe

#include "variant.h"
#include "due_can.h"
#include "Arduino.h"

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

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);

unsigned int localPort = 8888;      // local port to listen on

// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,

EthernetUDP Udp;

void setup() {

Can0.init(250000);
Serial.begin(9600);

Ethernet.begin(mac, ip);
Udp.begin(localPort);

}

void loop() {

    int packetSize = Udp.parsePacket();
    Udp.read(packetBuffer,packetSize);

   if (packetSize)
  {

    int Canframestosend= packetSize/8;    //Divides the Ethernet packet by 8 to match with CAN packet
    int count =0;
    int Rest=packetSize%8;                //Needed if the Ethernet packetsize isn´t a multiple of 8

    for(int j=0;j<=Canframestosend;j++){

    CAN_FRAME NewFrame;                   //CAN frames which are sent
    NewFrame.id=0xFA;                     //ID of the frames
    NewFrame.length=8;                    //Maximum of bytes a Can frame can have

    for (int i=0;i<8;i++){

       NewFrame.data.byte[i] = packetBuffer[count]; //Write the Ethernet info byte by byte on the CAN frames
       count++;
       }
    if(packetSize<count){
      NewFrame.length=Rest;                         //Shortens the last frame to avoid unnessecary zeros
      }
       Can0.sendFrame(NewFrame);

      }

   }
   delay(10);
}

Maybe there is an endless Loop but I don´t know which and why.

Hope anybody can help me with that!

I'd guess it's in the if(packetsize) logic -- if you get a packetsize of zero, you still try to read into a zero-size buffer and who knows what would happen.  Move the read inside the if(){...}

See https://www.arduino.cc/en/Reference/EthernetUDPRead

Also, you want to limit the reading to the UDP_TX_PACKET_MAX_SIZE size of the buffer, not to the size of the packet.

Update: The UDP_TX_PACKET_MAX_SIZE is only used in the user code, and nowhere else within the Ethernet Library.  You could use a larger buffer if you need to by defining and allocating a larger buffer and specifying its size in  EthernetUDP.read()  (see https://www.arduino.cc/en/Reference/EthernetUDPRead).


How to operate under linux an USB to I2C adapter based on the FTDI FT232R? How can I easily use, from the command line, the USB to I2C adapter based on FTDI FT232R?

I wrote a simple python script which implements the protocol for single byte transmissions (R/W).

If there is interest/requests, I can extend it.

code below:

#!/usr/bin/python
#
# Copyright (c) 2016, Igor Stoppa <igor.stoppa@gmail.com>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU General Public License,
# version 2, as published by the Free Software Foundation.
#
# This program is distributed in the hope it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#

'''
Simple script for driving the USB-to-I2C adapter based on the FTDI FT232R.
References:
Adapter:      http://www.robot-electronics.co.uk/htm/usb_i2c_tech.htm
Chip:         http://www.ftdichip.com/Products/ICs/FT232R.htm
I2C protocol: http://www.robot-electronics.co.uk/i2c-tutorial
'''

def parse_args():
    '''
    Process command line options.
    '''
    import argparse

    def auto_int(x):
        return int(x, 0)

    parser = argparse.ArgumentParser()
    parser.add_argument('-a', '--address', type=auto_int,
                        help='The 7bit address of the slave.')
    parser.add_argument('-p', '--port', default="/dev/ttyUSB0",
                        help="Serial port provided by the adapter. "
                             "Must have sufficient rights to open it R/W.")
    subparsers = parser.add_subparsers(dest='subcommand')
    #  subparser for write
    parser_write = subparsers.add_parser('write')
    parser_write.add_argument('-r', '--register', type=auto_int,
                              required=True,
                              help='Hex id of the target register - 1byte.')
    parser_write.add_argument('data', nargs = '*', type=auto_int,
                              help='Device dependent amount of data.')
    #  subparser for read
    parser_read = subparsers.add_parser('read')
    parser_read.add_argument('-r', '--register', type=auto_int, required=True,
                             help='Hex id of the target register - 1byte.')
    parser_read.add_argument('data', type=auto_int,
                             help='Device dependent amount of data.')
    return parser.parse_args()

def get_serial(port):
    '''
    Open the port with the adapter parameters.
    '''
    try:
        import serial
        ser = serial.Serial(port=port,
                            baudrate=19200,
                            parity=serial.PARITY_NONE,
                            stopbits=serial.STOPBITS_TWO,
                            bytesize=serial.EIGHTBITS,
                            timeout=0.500,
                           )
    except OSError as e:
        import sys
        print  e
        sys.exit("Could not open " + port)
    return ser

def write(ser, addr, reg, data):
    '''
    Use the adapter-specific protocol for writing out data.
    '''
    I2C_AD1 = 0x55  # R/W one or more bytes for 7bits addresses.
    ser.write(chr(I2C_AD1) + chr(addr) + chr(reg) + chr(len(data)) +
              "".join([chr(i) for i in data]))
    # Read the retval. Leaving it in the buffer of the PIC will cause
    # read mismatches in following read operations.
    if ser.read() is 0:
        import sys
        sys.exit("Failure writing.")

def read(ser, addr, reg, data):
    '''
    Use the adapter-specific protocol for reading in data.
    '''
    I2C_AD1 = 0x55  # R/W one or more bytes for 7bits addresses.
    ser.write(chr(I2C_AD1) + chr(addr + 1) + chr(reg) + chr(data))
    return " ".join(['0x' + format(ord(i), '02x') for i in ser.read(data)])

if __name__ == "__main__":
    args = parse_args()
    ser = get_serial(port=args.port)
    if args.subcommand == 'write':
        write(ser=ser, addr=args.address, reg=args.register, data=args.data)
    if args.subcommand == 'read':
        print read(ser=ser, addr=args.address, reg=args.register,
                   data=args.data)


U8glib funny problem I have strange problem with u8glib library. I have code:

void void_Menu_draw_func_men()
{
  if ( menu_redraw_required != 0 ) {
   u8g.firstPage();
    do  {
     Menu_draw_func_men();
   } while( u8g.nextPage() );
   menu_redraw_required = 0;
  }
}

void Menu_draw_func_men()
{

  u8g.setFont(u8g_font_6x13);
  u8g.drawStr(30, 0, "Funkcje");
  u8g.drawStr(15, 15, "Zerowanie modulu");
  u8g.drawStr(15, 30, "Modul na max");
  if(menu_pos == 0){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,20);}
  if(menu_pos == 1){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,35);}
  u8g.setPrintPos(5, 50); u8g.print("R:  "); u8g.print(pot_R , 2); u8g.print("   L:  "); u8g.print(pot_L , 2);

  Serial.println("func md");//just for check...

}

And oled display shows only cursor and I can move that cursor as I change menu_pos value. But no letters or values are printed on screen. Only cursor...

If I copy and paste only code from void Menu_draw_func_men(); to other part of my program:

void void_Menu_draw_test_man()
{
  if ( menu_redraw_required != 0 ) {
   u8g.firstPage();
    do  {
     Menu_draw_test_man();
   } while( u8g.nextPage() );
   menu_redraw_required = 0;
  }
}
void Menu_draw_test_man()
{

  u8g.setFont(u8g_font_6x13);   //replace this dwo lines
  u8g.drawStr(0, 0, "wykonywanie tefsdfs man...");

}

Everything works perfect... I was trying to change void name, and I don't know where is problem...
This is on Arduino Uno; I have 66% used of program memory, and 60% used of dynamic memory.
Maybe you have some idea?...

Your void_Menu_draw_test_man() function checks menu_redraw_required

Does your other part of the program update that variable? Do you call void_Menu_draw_test_man() from the loop() function?

It may help if you show the complete code, rather than small segments, since there are variables, such as menu_redraw_required, which are not changed anywhere in what is visible.

Note also that u8glib is no longer updated in favor of u8g2


Serial.read() doesnt work in IF statement I am working with an XBee module, so naturally, I started my void loop with AT command testing.

void loop() {
    digitalWrite(Sleep_Rq,LOW);

A +++ with a guard time of 1 sec before and after it, sets xbee module in command mode.

delay(1000);
xbeeSerial.write("+++");              // Enter Command Mode
delay(1000);

This part of the code, puts the serial data into string variable x in the form of a String.

while(xbeeSerial.available()) {
    x = xbeeSerial.readString();
}

Serial.println() is returning OK onto the serial monitor.

Serial.println(x);

But when I compare x with OK nothing happens, 1 doesn't appear on the serial monitor.

if(x=="OK")
  {
   Serial.println(1);
  }
}

I tried swapping "OK" with 4F4B (ascii equivalent of OK), 20299 (decimal value). I also  tried changing datatype of x from String to word and compared x with 0100111101001011.
I also tried changing the IF condition as,

if(Serial.println(x)=="OK")
    {
     Serial.println(1);
    }

and many more techniques with no luck to be found.

Your problem is that you are assuming that all you see in the Serial Monitor is all there is. You see "OK", so you expect to compare the text that comes in with "OK".

However it's not. Serial communication (at least, text based serial communication) generally includes some kind of line ending marker. That could be any combination of Carriage Return (\r) and/or Line Feed (\n). Different devices use different combinations.

As it turns out the XBee uses '\r' as the line ending marker.

There are two ways of dealing with it:

Include the line ending in your comparison ("OK\r"), or better,
Incorporate the line ending in the reading.

The second point there involves the use of readStringUntil():

String x = xbeeSerial.readStringUntil('\r');

That is a more reliable way of reading the response since it reads everything up to the line ending, rather than reading until it times out with nothing else to read. You should find your whole program runs smoother with that method.


ATmega328 is not recognized by software I installed the required drivers for the board. But I cannot still upload a program to the board. It says that

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

     System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : usb
     Using Programmer              : stk500v2

avrdude: usbdev_open(): did not find any USB device "usb" (0x03eb:0x2104)

avrdude done.  Thank you.

An error occurred while uploading the sketch

Can be many causes since you did not provide more info (like what circuit, what application). But in general:

Wrong software installation
Try another similar chip/device, maybe this one is broken
Is it recognized by USB at all?
Bad USB cable
Did you select the right board in the IDE (Arduino IDE?)

Possible solution:

Reinstall IDE
Change chip
Change Arduino
Use different cable


I fried the AMS1117 voltage regulator on my Arduino Clone, is this the cause? I had the 12V DC power jack plugged-in all the time, and "to make things more exciting" I also plugged-in the "data" USB whenever I had a new sketch to upload. Is this combination a big no-no, or is my step-up converter to blame?

I am completely new to this stuff but now when thinking of it those 12V from the power jack + 5V from the "data" USB probably violate this clause:
If using more than 12V, the voltage regulator may overheat and damage the board.

The "problem" with the AMS1117 voltage regulator is the amount of current they can safely provide drops as the input voltage rises. I'm a Arduino noob, so I looked at the data sheet for the AMS1117 series of voltage regulators. There is a formula: PD=(VIN-VOUT)(IOUT) and Note 2: which says the maximum power dissipation for the SOT-223 package is 1.2 W.

The best case scenario is to use an input voltage of 6.5 volts. (6.5-5)(0.8)=1.2W. This gives you 0.8 amps maximum output. If you use a 12 volt power supply: (12-5)(0.1714)=1.2W. This only gives you 0.1714 amps maximum output.

I'm not sure what kind of power jack you are using, so I'll give you an example of one that I used in a project. It says input 120VAC, output 12VDC, 200ma. The problem is, it actually puts out 20VDC open circuit with no load.

The data sheet gives a maximum input voltage of 15 volts but that would only provide a maximum of 120 mA output.


Stepper Motor won't reverse/turn CCW Before bothering anybody, I've been Googling this issue for the last three weeks and have not been able to solve the issue, so must reach out for help.

My son has done multiple Arduino projects after having a Creation Crate subscription, and now we're working on a project together.  We bought a 28BYJ-48 stepper with driver, and figured it'd be just a question of copy-and-paste coding and we'd be in business.

I've tried the Arduino library, the AccelStepper library, countless other sketches from various websites and for some reason the stepper only vibrates when it's supposed to turn CCW.  There was one sketch we were using that used Serial Monitor to enter in the number of steps, and when i'd do a minus number of steps, it'd go CCW, but the next day no longer would!  I thought this was a motor or driver issue, but we've bought three more motor/drivers and still have the same problem.  In researching an answer, I've seen some people say to switch IN 3 & 4 but I still get same results.

We've been connecting 8 to IN1, 9 to IN2, 10 to IN3 and 11 to IN4.  Using a separate 5V power supply to the driver which is also grounded to the Arduino (have tried both ground pins just in case that makes a difference, but no).  We've also tried changing for another Arduino and this hasn't made a difference either.

we've tried multiple sketches from multiple sources, here's one as an example:

#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  // set the speed at 60 rpm:
  myStepper.setSpeed(60);
  // initialize the serial port:
  Serial.begin(9600);
}

void loop() {
  // step one revolution  in one direction:
  Serial.println("clockwise");
  myStepper.step(stepsPerRevolution);
  delay(500);

  // step one revolution in the other direction:
  Serial.println("counterclockwise");
  myStepper.step(-stepsPerRevolution);
  delay(500);
}

The Serial Monitor will state that it's turning CCW, but it isn't.  Any help would be much appreciated!  What we thought would be a simple step in our project has become a major roadblock!

I had this issue myself, when I tried to use these stepper motors (which are to be honest really crappy ones, but very cheap). Vibrating mostly means, that the phases of the motor are not activated in the correct order. These motors seem to work with an activation pattern for half steps (I don't know, if the motor is really doing half steps with this, because I didn't counted them for a whole revolution. But at least they worked). The Stepper library (I assume from your code, that you are using this one) isn't meant for this driver, so it will turn on the phases in a wrong order and always two phases at the same time (as for full steps).

I had success, when driving the 4 phases of the driver with the following pattern (for half steps):

1000
1100
0100
0110
0010
0011
0001
1001

I also found hints on the web (on a german site, just for reference, if you can read german), that - despite being meant for half steps - you can drive the motor with full steps with the Stepper library as well. You would have to change the order of pins in the definition of the stepper:

Stepper myStepper(stepsPerRevolution, 8, 10, 9, 11);

This assumes the wiring as: D8->IN1, D9->IN2, D10->IN3, D11->IN4. Note, that using full steps means 2048 steps per revolution.

I also found a library specific for this stepper motor, but I haven't tested it: Stepper_28BYJ_48

Now you can decide yourself, which way you want to go. I personally would go for the full steps with the official Arduino Stepper library.

About the number of steps per revolution: I don't know, why the stepper doesn't work with a vale of 2048. But since the library only uses this to wrap up the correct phases for the revolutions, you can use a lower value, that is dividable by 4. For example 32, which is the number of full steps per revolution of the actual motor (it is attached to gears with a factor of 64). That should work.


Arduino log file directly to file I have problem because I need to read values and then save them in a .txt file, but Arduino doesn't have a physical connection with my computer. It only has a connection with a computer using Ubuntu without Arduino IDE or other programs. Also, I don't have an ethernet connection and SD card. I need only to have this data stored. The best way is to send them at the end of cycle to a special text file. Has anybody faced that before?

I'm thinking about writing a bash script for reading all values sent by serial and then save them, but how do I get that information from serial?

Any serial terminal emulator application can connect to the Arduino. Select one that has log-to-file capability and open its log file after you've connected it to your Arduino's /dev/tty... device.

Start the Arduino and let it collect & send the data to your terminal program. Close the terminal app's log file (easy step to forget - ask me how I know :) and there's your data.


Arduino Due for camera control? Could one use the Arduino Due to control camera module like OV5642 and send the data to spi device? My project is to capture image with OV5642 and then to send the image data(RGB565) to other device via spi. For this STM32 must be enough, but I'd be happy if I can use the arduino IDE. Because it is much easier to program.

Could you please let me know, if you can use the Due for this task?

You are still not giving the full picture, pun intended.

I'll give you an example of what sort of info is missing.

For example, what's the frame rate? What's the color depth of the sensor?
If you look at the SAM3x TRM, it says that the SPI is clocked at max 65MHz.

So, the (simplified) math would say:

24bit/pixel * 5Mpixel / 65MHz =  1.846 seconds

And that doesn't even account for acquisition time, so if you do not have fully working DMA on both sides, it's probably even worse.
And it will be worse, because you cannot stuff in RAM in one go the entire image.

But maybe that's good enough for you, however it's not possible to say because of the missing info.


How to program a Arduino Nano(Bricked) with a working arduino nano I corrupted my bootloader on one arduino, luckily I had a spare lying around. Please help as there is not a single tutorial to help my exact state

I have a page about programming a bootloader using another Arduino.

Basically you grab the code from here and then make up wiring from the good device (which you put the sketch onto) to the device to be programmed, like this:

Arduino Nano        Target Nano

D10 (SS)            Reset
D11 (MOSI)          D11
D12 (MISO)          D12
D13 (SCK)           D13

Gnd                 Gnd
+5V                 +5V


Way to use other baud rates in console or different input/output rates I want to send some test codes to a MIDI synthesizer, so I wrote a program that lets me just type in hex codes on the serial monitor and send it over serial as the byte value. For example typing "90 45 63" should turn on note 0x45 with a velocity of 0x63.  This part works ok and I have the arduino hooked up to a midi connector and from there to a midi synth. I've verified that this works ok with some test code.

Where I'm having trouble is that MIDI requires a rather unorthodox baud rate of 31250.  The problem is then that on an Arduino Uno, I don't see how I can enter serial data when the Arduino's serial monitor doesn't allow that baud rate. Also trying to set that baud rate under Linux using stty generates an "stty: invalid argument ‘31250’" error.  So is there a way to use a different baud rate for input than for output or some other solution here?  I do have a Teensy 3.1 with multiple Serial ports, but its kinda tied up at the moment and I just thought I could use an Uno for this.

UPDATE: It works now. Something to keep in mind when working with complex external components like a professional synthesizer. The Roland JV-880 that I'm interfacing with wasn't receiving program changes even though I was sending the 0xC0 0x03 codes or whatever. This is why I made this debugging program to begin with. After searching around and being stumped, I looked around the system settings on the synthesizer and discovered a setting called "System MIDI Rx switch Program change=OFF". After I changed that to ON the program change codes worked. Sometimes the problem is nothing in your code or circuit.

The Arduino Uno is powered by an ATmega328P microcontroller. This
microcontroller has only one UART which is not capable of using
different baud rates for sending and receiving.

You could look into the different software serial port implementations
for the sending side. Another solution would be to continually change
the baud rate: each time you get a complete message from the serial
monitor,

you switch the baud rate to 31250 bps
you send the packet to the midi synth
you Serial.flush() to make sure the bytes have actually been sent
you switch back the baud rate to whatever you used in the serial
monitor

You will probably see some garbage on serial monitor as it receives the
bytes at the wrong rate, but that should not be an issue.


Arduino - fuse setting problem on ATmega328P-PU I am trying to do fuse setting on ATmega328P-PU chips using an avr programmer.

I was successfully able to do fuse setting on 3 ATmega328P-PU chips (which I bought from one of the sites - I forgot). So I bought three more from Amazon.

When I execute avrdude -c usbasp -p m328p on the previous 3 chips, I got this response, and was able to do fuse setting.

  avrdude: warning: cannot set sck period. please check for usbasp firmware update.
  avrdude: AVR device initialized and ready to accept instructions

  Reading | ################################################## | 100% 0.00s

  avrdude: Device signature = 0x1e950f (probably m328p)

  avrdude: safemode: Fuses OK (E:FF, H:D9, L:E2)

  avrdude done.  Thank you.

But when I execute the same command on the 3 chips I recently bought, I am getting this.

avrdude -c usbasp -p m328p

avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
     Double check connections and try again, or use -F to override
     this check.

avrdude done.  Thank you.

I triple-checked the wiring and soldering area. They all look fine.

Is this because the 3 chips I recently bought have a bootloader?

The description for the chip that works is here.

The chips configured with a bootloader would also have the fuses set for an external clock (the factory default is the on-chip oscillator). Without an external clock they won't work.

I have a sketch that uploads files that also can provide an external clock for this eventuality.

As mentioned on that page an 8 MHz clock is provided on pin D8 of the programming board, so you can connect to D8 on the Uno which you are running the sketch on to pin 9 on the actual Atmega328P chip.

Alternatively find a 16 MHz crystal or resonator and connect that between pins 9 and 10 of your Atmega328P which will provide the clock that it is expecting. If you use a crystal you should also run 22 pF capacitors between each leg and ground, like in this image:


What programming practices should be adopted while coding sketches for Arduino? What are some of the best programming practices that can be adopted while coding sketches for Arduino, so that it uses the least memory and performance should not suffer from memory outage, and still the code be robust?

From the link: https://www.arduino.cc/en/Products/Compare

I have learned that the Uno has 32 KB of Flash memory. The maximum available is in the MEGA with 256 KB. I think Uno and Mega are the most widely used by people.

Paul covered the most important points. This answer is intended to be a
complement to his.

First, you should keep in mind the general rules, which are more
important than the more specific ones. The general rule for saving RAM
is: be aware of what you are storing, and do not store anything you do
not really need. The general rule for saving flash is: be aware of what
you are doing, and do not do anything you do not really need.

Now, a few specific tips:

Use the const qualifier for declaring constants (e.g.
const int ledPin = 13;). The compiler will optimize-out the storage of
the constant and use immediate addressing instead.

Use PROGMEM for arrays of constants.

Whenever possible, use static memory (globals and static locals)
rather than heap allocation (malloc() and new). This will prevent
memory fragmentation and make the memory usage more predictable (only
the stack holds dynamic memory): you know at compile time, rather than
run time, whether you are low in RAM.

For the same reason, prefer C strings (char *) over String objects.

Use the C99 types int8_t and uint8_t whenever 8 bits are enough for
your integer variables.

Use the static qualifier for functions that will be used only in the
same source file, especially for functions that are called only from one
place. This gives the compiler more optimization opportunities.

If you need to optimize,
use avr-nm to know what is
consuming your precious RAM.


Hook Arduino up with thermal printer and power both externally Disclaimer: I have no connection to adafruit.

A friend and me want to build a little project. We want to connect an arduino to a thermal printer and then print out little fortune-cookie like messages, when a button is pressed. The whole setup should not be stationary and thus we need external, mobile power like batteries.

Since this is our first time using an arduino as well as a thermal printer and we have no clue about electronics, I am asking for help to set everything up without frying the arduino or the thermal printer.

We are using a standart arduino uno rev3 and the Adafruit Tiny Thermal Reciept Printer.

First question: Setting up the power supplies

So the idea was to power the arduino via a 9v battery pack to it's 2.1mm DC port. I think this should work, right?

What I am confused about is the Adafruit Tiny printer. It says it takes 5-9 V, 1.5-2A. Can I just hook up a 9V battery packand clip the caples to the printer? Or what setup do I need so that the printer will recieve enough amperes when printing?

And how would I connect both tools to a single ( larger ?) battery pack?
So that we can turn the power off easily?

Second question: Finding a good button compatible with an arduino and setting it up in the project.

So we have a gerneal idea of how things should work. Somehow we need to connect the button to the arduino which then can register a click via one of it's pins. This click I can then register with my code and from there on things get easy for me. But getting to this point is hard for us.

We don't know which buttons will work and neither how to connect it to the right pin. Which pin should we adress? Digital? Analog?
Does the button need an external power supply as well? Since otherwise the arduino would not register a change of current on a pin, right? Or do we need to connect the button to the whole circuit?

I do a lot of high language engineering and have no real idea about circuits and electronics and my friend is more of a craftsmen so we really appreciate your ideas, setups and help in general!

I am not sure if this is too much to ask but a sketch of the whole setup with a single power source and button would be awesome! Thanks. Really!

Setting up the power supplies

As Gerben already stated in the comments, a 9V block battery isn't capable of supplying enough current for the thermal printer, so you cannot simply use one of them (these are meant for low power applications, like a smoke alarm). There are many different types of batteries, that you can use for this. Probably some kind of LiPo or LiIon pack would be suitable. (I'm sure you can find information about pros and cons of different battery types on the web). But the easiest way for you would be an USB power bank, that can supply at least 2.5A. A power bank incorporates mostly a LiIon pack and also already the mandatory smart charging electronics (to charge and discharge correctly and also to monitor the charge level), and - every important - a 5V voltage regulator. You can supply the 5V from the USB power bank directly to the Arduino and thermal printer in parallel. If you need to switch them on and off together (and the power bank doesn't already incorporate some kind of switch), you can use a simple switch between the positive lead from the power banks USB port and the positive leads for Arduino and printer.

  Finding a good button compatible with an arduino

Every normal button is compatible with Arduino. A button is nothing more as a switch, that automatically opens again, if you are not pressing it. Just two pieces of conductive material, that get's pressed together, if you press the button. A normal button has 2 pins (you might see more pins on the button, but mostly some of these are electrically connected together, so that you effectively have only 2 pins). Connect one pin to ground and the other to a digital input pin of the Arduino. Then in your sketch use pinMode(pin_number, INPUT_PULLUP); in your setup() function. This will enable the Arduinos internal pullup resistor, which pulls the pin to HIGH, if the button isn't pressed. If you press the button, the pin will be pulled to LOW. Keep this inverted logic in mind (LOW means pressed, HIGH not pressed).

There are also many button examples for Arduino on the web, since using a button is the second thing to learn with Arduinos (after blinking an LED). Button example code via digitalRead() is also incorporated into the Arduino IDE (look for examples in the menu).

  a sketch of the whole setup

Even, if someone wanted to write the code for you (and this is not a free coding service, so you cannot expect someone to simply do it), you haven't given us enough information, what behavior you want. But please don't add that here, to get this free code. What you are asking (single power source and button) is not difficult. Surely - currently you don't know much about this stuff, but it's not rocket science and there are many many Arduino tutorials on the web to help you. About the code for the thermal printer: Adafruit always provides dedicated guides for the devices they sell. There you can find a description, how the device works and is connected and used. They also provide example code and in most cases complete Arduino libraries, that hide most of the complexity of a task.

You should start by connection the Arduino to the power bank. Then you should go on and get the button going (you can write a sketch to turn the onboard LED on and off with it to learn how it works). Then you can connect the printer. Try adafruits example code. If it works, you can extend your sketch with the printers code.

Note: Some power banks turn of the power completely, if only a small current is flowing out of if. With such a power bank your Arduino might turn of as the power bank cuts the power. It normally does not draw enough current for the power bank. I think this shouldn't happen, when the printer is connected, but this depends on the current, that it draws (considering the minimal current, that it draws while idling), and the current, that is the minimal limit for your specific power bank.


nRF24L01 - Measuring distance using time elapsed For school usage, my team and I are working on a wristband that will alert the user if they are too close to another wristband (for social distancing). The problem is measuring distance using radio waves. Since I cannot use signal strength, I'm thinking about calculating distance from time taken to transfer some data and velocity (which will be around the speed of light). I discarded the idea of using ultrasound because it is too easily interfered with by other obstacles.
My plan is along the lines of this:

Sensor 1 and 2 are synchronised to a clock.
Both will run a
"stopwatch", and the time values should be exactly the same at the
same time.
Sensor 1 sends out a message to Sensor 2. The message
contains the time at which the transmission started.
Sensor 2
receives the message, immediately records the time of reception, and
calculates the time taken for data to travel
d = v/t
Vice-versa

If the distance is smaller than the radius, a warning is triggered in the form of a vibration motor.
Limitations include clock speed; I intend on using a Seeeduino XIAO, an Arduino-compatible board. The clock speed is max. 48MHz, meaning that the smallest increments it can measure is 20.82 nanoseconds. I also calculated that it would take 13.33 nanoseconds to travel two metres (the former distance to keep in public). Hence, with the clock speed available to me, I can only measure 3m and beyond.
Assuming I was happy with this distance, would I be able to do this using one single Arduino sketch? I know that Arduino programs can only run one at a time. Would a constant background clock/stopwatch be too complex? Could you give me any other pointers?

Speed-of-light-delay measurements are not practical for the use-case you propose. As Majenko suggests in his comment, you'd need EXTREMELY accurate time measurement, as well as high speed radio-frequency signal processing. Any measurements you do through software will be far too inaccurate as a result of the software timing.
Apple's iBeacons (which are based on BLE) offer immediate, near, medium, and far distance readings that are based on signal strength. You should be able to achieve something similar with your own wristbands using BLE. The different distance thresholds would have some slop to them, but it should be possible to get decent results.


Trying to use an LCD 1602 to display, but I don't have a 10 KOhm potentiometer I'm following this tutorial page and I don't have a 10k ohm potentiometer on hand. Could I replace it with resistors to simulate a manual setting and replace the resistors to adjust to a new settings.

From what I was reading this pin is for contrast and I'm sure I could manually set the contrast once and be happy with it for quick prototyping. I'll be ordering a 10k ohm potentiometer on Monday.

Yes. All a potentiometer is, is two resistors end to end.  The "wiper" is the join between the two resistors.

It doesn't matter too much what value potentiometer (and hence what value resistors) you use, as long as it's "around" the 10kΩ mark (100kΩ should be fine, 50kΩ, 1kΩ etc - anything below 1kΩ may not work) - what matters is the ratio of the values of the resistor.