HD44780 DDRAM addressing on the second line I write bytes to HD44780 display DDRAM to display characters and it works weird on the second line. I use 16x2 model and I write "0123456789" string from address X on.

According to the datasheet:

  In a 2-line display, the cursor moves to the second line when it passes the 40th digit of the first line.

So when I set X to 40, the string appears from the beginning of the second line. So far so good. But when I change X to different values, this appears on the second line:

X=39 ... 123456789
X=40 ... 0123456789
X=41 ... 0123456789
...
X=47 ... 0123456789
X=48 ... 89
X=49 ... 789
...
X=56 ... 0123456789
X=57 ... 0123456789
...
X=64 ... 0123456789
X=65 ...  0123456789
X=66 ...   0123456789

Since address X=64 it works as expected, so increasing X by one shifts the string to the right by 1 character. The datasheet also says

  However, when N is 0 (1-line display), AAAAAAA can be 00H to 4FH (79). When N is 1 (2-line display),
  AAAAAAA can be 00H to 27H (39) for the first line, and 40H (64) to 67H (103) for the second line.

So the second line starts at 40H (64), not 40, it seems. Is it a confusion? What is the idea between address 40-64? It would make sense if the second line was address 28H-40H. I don't see the explanation in the datasheet. Also, how the DDRAM works for 20 characters per line and 4 lines displays?

Your confusion here is mixing "digit" and "byte". The two are not the same.

HD44780's can never have more than two rows. If you look at the block diagram you can see there are 16 "COM" connections. Those are the rows of the characters - 8 per line. That gives at most 2 lines of text.

20x4 displays are actually 40x2 displays but sliced in half and stacked. The 21st character of the first line is actually the first character of the 3rd line.

These two lines are split into two separate blocks of memory. One starts at 0x00 and the other at 0x40. The two blocks are pretty much completely separate.  There is nothing of any interest to you between 0x28 and 0x3F. In fact that memory may not even exist - however those addresses may map to other addresses within memory. This will purely be an artifact of how the memory is addressed internally.

For simplicity of decoding the addresses the two blocks of memory are distinguished purely by the most significant bits of the address. The lower bits, then, will always be the same for the same location in both lines of text. That is, for the same horizontal character position on the display the first row (COL0-COL7) will have the same address in memory as the second row (COL8-COL15) except the most significant bits.

Since the HD44780 operates in blocks of 40 bits (8 characters, 5 bits per character) for its displays and uses "extension modules" to give each extra block of 8 bits (which is why you get 8, 16, 20, etc widths) having the two lines of text with truly consecutive memory addresses would make decoding the addresses needlessly difficult. So they don't.

If you take an example of the 3rd character horizontally on the display the pixel address in memory will be (note: this is the pixel address, which is 5x what the character address would be after the data has been generated from the internal character set):

Line 1: 0x02 = 0b00000010
Line 2: 0x42 = 0b01000010

Since the memory itself is 80 bytes and designed to be no more than 40 characters wide with 1 or two rows, there necessarily has to be a dead zone between the blocks of addresses. If the addresses were completely contiguous, so that the first character of the second row (character 40) was the 40th address in memory, the memory addresses would look like this:

Line 1: 0x02 = 0b00000010
Line 2: 0x2a = 0b00101010

Mapping those two addresses to the signals COM0-COM7 and COM8-COM15 would be considerably harder and take far more complexity in the design of the chip - which the manufacturer certainly doesn't want.

It is far simpler to add a little bit of logic into the cursor control which says "If the cursor moves from position 39 to 40 then set the memory address to be 0x40".

So when writing successive characters to the display the cursor logic hides the segmented memory from you. But if you are directly manipulating that segmented memory then you have to take that segmentation into account.


Different Arduino packages on Raspbian I'm working on using my Raspberry Pi (Raspbian) to upload sketches. However, I'm not sure which package is appropriate for command line usage (like described here on Github).

It seems like sudo apt-get install arduino would install the whole IDE, not just the command line. It seems like arduino-core would be more fitted for this purpose. However, the repository has a note online to use a package called arduino-mk for a CLI, which is what I want. However, this concerns me in the repository's page:

  This package will install a Makefile to allow for CLI programming of the Arduino platform.

(Emphasis mine)

What exactly does this mean? What are the differences between the three packages available?

I have not actually interacted with the debian packages, but If I'm reading this right, this how they are organized:

arduino: The whole java IDE and avr code libraries

arduino-core: the libraries and code that comes with arduino to be compiled for avr

arduino-mk: a makefile for compiling arduino code without the IDE (but no code)

The normal arduino package has a command line interface, but the code for this is (currently) very closely tied to the java GUI code and cannot be used without the whole thing being installed. To make using the raw atmel avr tools easier, the makefile is available; However, the makefile does not include all of the cpp libraries that come packaged with the arduino installation that a normal arduino sketch would reference (Arduino.h, Servo, SPI, etc). The arduino-core package exists to bring in all this supporting code.

I imagine it is done with these three packages so if you already have arduino installed, the makefile will not bring a second copy of all the libraries with it.

The makefile is a configuration for the gnu make software. There is some information on the specific usage of the arduino makefile on its github page here


Simple Arduino Bluetooth Shield Android Display I need help with my Arduino code. Here is my setup:

LM35 connected to Arduino with output connected to Analog 0.

Temperature computation work and serial monitor displays the correct reading.

I want to connect via Bluetooth to an Android app to display the temperature.

It displays it a few times but 98% of the time it doesn't display it on the app. I'm thinking the problem may be in the code that I have:

#include <SoftwareSerial.h>

#define RxD 6
#define TxD 7

float temp;
int temperaturePin = 0;
float  temp1;
SoftwareSerial blueToothSerial(RxD, TxD);

void setup() {
  Serial.begin(9600);
  pinMode(RxD, INPUT);
  pinMode(TxD, OUTPUT);
}

void loop() {
  temp = analogRead(temperaturePin);
  temp1 = temp * 0.48828125;
  Serial.print(temp1);
  delay(1000);
  blueToothSerial.print(temp1);
  delay(1000);
}

I just really want to make it simple. Kindly help.

You need to terminate the string sent by adding blueToothSerial.println(""); after blueToothSerial.print(temp1);. As it is the code doesn't terminate the temperature string with an LF char, and the Android app thinks it hasn't received the full string yet.

void loop() {
  temp = analogRead(temperaturePin);
  temp1 = temp * 0.48828125;
  Serial.print(temp1);
  delay(1000);
  blueToothSerial.print(temp1);
  blueToothSerial.println("");
  delay(1000);
}


Is extra hardware and components needed to connect the bare MCU directly to a PCB, without a shield? As a hobbyist I code in a variety of arduino's and in Digispark's (Attiny 85 and 167).
But I'm doing a project with space contraints, so I'd need to use just the MCU directly over my pcb.
Apart from a voltage regulator (to get the VIn to 5V or 3.3V) do I need extra components to mount the MCU to my PCB?
DO I need crystals, capacitors, etc? Or the MCUs (mostly AtMega 32u4 and Attiny85 and Attiny167) have it all what's needed inside them?
I'll program the MCU before soldering on to the PCB, so there's no need for USB or programming stuff or leds.
Thanks!

DO I need crystals, capacitors, etc? Or the MCUs (mostly AtMega 32u4 and Attiny85 and Attiny167) have it all what's needed inside them?

You don't need a crystal if you use the internal clock of the MCU (which means setting the fuses right and compiling your code to expect the right clock frequency). However if you are using a direct USB interface (such as for the ATMega32U4) then you will need a crystal as the precise timing is required for USB to operate.
You will need capacitors. Decoupling capacitors on all the power pins are not optional and must be included.
You will need a pullup resistor on the RESET pin unless you have set the fuse to disable the RESET pin (not advisable since it will prevent ICSP programming in the future - but can be useful for low pin-count chips).


Send structure through Serial Suppose that one defined a data structure and wanted to send it through serial.

 struct Gyro_data_structure {
    char command_name[5];
    float gyro_X;
    float gyro_Y;
    float gyro_Z;
};

Gyro_data_structure Gyro_data;

int size_gyro=sizeof(struct Gyro_data_structure);

void setup() {
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop() {
  Gyro_data.command_name[0]='H';
  Gyro_data.gyro_X++;
  Serial.println(size_gyro);
  delay(500);
  Serial.write(Gyro_data,size_gyro);
}

However, it returned an error saying "no matching function for call to 'HardwareSerial:write(Gyro_data_structure&,int&)'". I googled and found Michaël Roy's answer here. However, it's not working: "can not convert ..."

How to send a structure through UART?

I tried the code from the link you posted and it worked:

struct Gyro_data_structure
{
    char command_name[6];
    int gyro_X;
    int gyro_Y;
    int gyro_Z;
};

struct Gyro_data_structure Gyro_data = {"Hello", 48, 49 , 50};

int size_gyro = sizeof(struct Gyro_data_structure);

void setup()
{
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop()
{
  send(&Gyro_data);
  Serial.println();
  delay(1000);
}

void send (const Gyro_data_structure* table)
{
  Serial.write((const char*)table, size_gyro);  // 2 bytes.
}

bool receive(Gyro_data_structure* table)
{
  return (Serial.readBytes((char*)table, sizeof(Gyro_data_structure)) == sizeof(Gyro_data_structure));
}

I changed the float type to int for easy representation. When you run the code the serial window will show: Hello012

Because Arduino IDE serial window shows ASCII characters. 0's ASCII value is 48 and so on.

Update

It depends on what you want from the read function. Let's break down what Michaël Roy's implementation is doing. First, he reads sizeof(Gyro_data_structure) number of serial bytes and put it in the variable that table points to:

Serial.readBytes((char*)table, sizeof(Gyro_data_structure))

The 2nd argument of readBytes() takes how many bytes you want to read. Also readBytes() return how many bytes it read. Let's say we stored that number in return_bytes. In the next part he did:

return (return_bytes == sizeof(Gyro_data_structure))

He is checking if the number of bytes readBytes() read is the same as the size of  Gyro_data_structure. If it is not, then return false.

This just tells you if you read more or less than what you are supposed to read. Regardless of true or false, the actual bytes that were read will be in the variable that you passed to the receive() function.

If you don't want the function to not return anything this is how it should be:

void receive(Gyro_data_structure* table)
{
  Serial.readBytes((char*)table, sizeof(Gyro_data_structure));
}


How to make C++ code compatible with Arduino IDE? I wrote some code in C++ (Used libraries like fstream, vectors etc.) Now when I transferred the code to Arduino it wouldn't compile so I added the following library: https://github.com/maniacbug/StandardCplusplus I downloaded the IDE from here: https://www.arduino.cc/en/main/software

Now almost all my code works: All the libraries I've used work except for fstream which I've used to read a specific file.

Now is there a certain problem with the 'StandardCplusplus' library and how can I counter this problem.

Plus can someone give me an alternative for fstream that works with Arduino. Was reading a bmp image using C++. Now fstream works in a certain way (reads the file in a certain way). Is there some alternative to fstream.

When you run that library on the Arduino and ask it to open a file, where do you imagine it would read the file from? Your Arduino has no hard disk or other file system.

One way to solve this is to include a library that emulates a read-only file system in the Arduino's flash. I dunno whether this exists (such libs do exist for for some other targets, for instance for the Nintendo DS), but it would be a bit of overkill IMO.

Another way is to include the data that is in the file in your program, as a const (expr) array of bytes, and read from that array instead of from the file. But if you have a library that is coded to use file read calls this would require some rewriting.

A third approach would be to do the reading and interpreting of the file on your host PC, output the interpreted content to a const (expr) byte array, and include that in your application. This frees you from having to include the bmp-read code in your image.


Best way to assign value to lot of variables I'm building web based remote control system for esp8266. In arduino IDE, using the ESP libraries. To, send data to the server, I'm using http post.
For some settings, I need to transfer 30 or so, different values over a single post request.  And assign it to different type of variables.

so, from this:
192.168.1.101/testpost?lenght=10&1=100&2=true&3=1800&4=125

i need this:

uint8_t brightness = 100;
bool randomOrder = true;
uint16_t Delay = 1800;
uint8_t Position = 125;

This is the relevant code. Basically, my idea is, to send the lenght of the array (will be different each time.) in the first argument.
Than create a for loop that put every value in a array into variable pointers. But, since lots of different type variables going on, i'm not sure how to do that.

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

//values i need to set in a single post.
uint8_t settings0;
bool brightness;
uint16_t randomOrder;
uint8_t Delay;

void setup {
//relevant code that handels post request.
server.on("/testpost", HTTP_POST, []() {

String ZeroValue = server.arg("lenght");

int lenght = ZeroValue.toInt();

//this doesnt really work, but its a starting idea.
int* SettingsArray[4] = {&settings0, &brightness, &randomOrder, &Delay};

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

     String PresetSettings = server.arg(i);
     SettingsArray[i] = PresetSettings.toInt();
    }
});
}

Ultimately, I can just do that, but I'm wondering if there is a more elegant solution.

brightness = SettingsArray[1];
randomOrder = SettingsArray[2];
Delay = SettingsArray[3];
Position = SettingsArray[4];

The WebServer class supports argument lookup by name. This should allow HTTP argument parsing that does not require length and/or specific order:

192.168.1.101/testpost?brightness=100&randomOrder=true&delay=1800&position=125

And parse with:

brightness = server.arg("brightness").toInt();
randomOrder = server.arg("randomOrder").toInt();
Delay = server.arg("delay").toInt();
Position = server.arg("position").toInt();

Please note that some value will require cast (and there might be a need for special handling of "true" and "false"). For further robustness each argument name needs to be checked that it is available.

String arg = server.arg("argName");
val = (arg.length() == 0 ? defaultVal : arg.toInt());

Or simply:

String arg = server.arg("argName");
if (arg.length() != 0) val = arg.toInt();

Cheers!


Small, Power-Efficient wireless communication with ATTiny85 For a project that I'm working on I need an extremely small, power efficient wireless device (could be radio, or some other interface) to network between a series of ATTiny85s and a larger Arduino. The communication range only needs to be about 1 foot, max. I'm currently using wired I2C, so it would be excellent if someone could suggest a radio or another device that can use the two digital pins previously occupied by the SCK and SDA lines on the ATTiny. I have those two, along with one extra digital pin available for use.

This device needs to be extremely small - this common NRF24L01 package is too big and its SPI interface uses too many pins.

Thanks for your help.

I've also had good results with using the Mchr3k - Arduino Manchester Encoding library with those 315mhz RF kits. It has support for ATTiny85 as well.


avrdude: stk500_getsync(): not in sync: resp=0x00 I have arduino pro mini 5V, 16M ATMega328 and CP2102 USB to TTL. I've wired them like this:

When I try to upload a sketch to the arduino board I'm getting the following error:

avrdude: stk500_getsync(): not in sync: resp=0x00

The board type and the serial port are correct. The sketch also compiles successfully and I've installed the CP2102 drivers. I've noticed that even if I unplug all wires from the arduino board(and just leave the cp2102 connected to the PC), I'm getting the same error again. I'm using Windows 7.

Anyone else encountered the same issue?

It's hard to tell from your pictures, but are all the header pins soldered to the boards? If not, they need to be: there's no chance that the proper electrical connections will be made reliably if they're just inserted loosely into the holes.


Connect a USB slave into Arduino using FTDI Probably I'm asking a nonsense question but I'm new at interfaces.

I want to connect an USB barcode scanner to an Arduino (Uno or Mega). I've read that I need a USB host shield to achieve this. But I don't have any. I have a FTDI, so I suppose I could plug the USB output of the scanner into the FTDI and connect the FTDI to the UART port of Arduino. Then, I would be passing the USB output to Serial.

Is it correct? Thanks and sorry if I said something stupid!

No, that is completely wrong.

In USB you have hosts and devices. A device has to connect to a host. Your FT232 is a device. The barcode scanner is a device. Both of them need to be connected to a host for them to do anything.

So you need a USB host shield to act as that host.

However - check the manual for your barcode scanner: it may well have a RS-232 mode that it can be switched into (may need a different cable attached).


How to store incoming serial string in arduino? In my recent project, I am working with serial data. Till now, I'm able to receive data and display on LCD. Now, suddenly I can't get any serial data. Nothing display on LCD.

My incoming string is:

{"Action":"ONE","TPS":"0.40","MAP":"0.95","LOAD":"14"}

And my code is below:

#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

String response = "";
bool begin = false;

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

void loop()
{

  while(Serial.available() || !begin)
  {
    char in = Serial.read();

    if (in == '{')
    {
      begin = true;
    }

    if(begin)
    {
      response += (in);
    }

    if(in == '}')
    {
        break;
    }
    delay(1);
  }

  lcd.setCursor(0, 0);
  lcd.print(response);
}

Actually I can see what I think may be an issue with your code.

 while(Serial.available() || !begin)

This isn't right.  If there is no data available in the serial buffer but the first { hasn't been seen then go and read the non-existent data anyway?

Rather than try and explain what I mean in multiple comments I have put it all together and this is what I think your loop should be this:

/// This is un-compiled code, so you might have to fix some little issues.
/// bool begin = false;         // True when the initial { has been seen

void loop()
{
  while (finished == false)
  {
    if (Serial.available())
    {
      const char in = Serial.read();
      if (in == '{')
      {
        response = "";  // Blank the string
        begin = true;
      }
      if (begin)
      {
        response += (in); // Only write if within the {}
      }
      if (in == '}')
      {
        begin = false;   // Prevent any chars between } and { leaking through.
        lcd.setCursor(0, 0);
        lcd.print(response);
      }
    }
    delay(1);
  }

  delay(500); // Not sure what will happen if you send multiple {} to the LCD too fast.
}


Formula for decision making when in contact with an obstacle using Arduino I am currently working on an obstacle avoidance robot project and I have seen numerous algorithms for obstacle avoidance a very good example is this Obstacle avoidance algorithm [Editor's note: by user3880651],
but unfortunately non of those algorithm works with Arduino so upon my research I found this blog

and in there the author talks about an effective way to avoid obstacles and even has a formula he uses for avoiding obstacles at different positions e.g (Front and sides) but doesn't really explain how he got the formula so I was wondering if anyone as an effective formula or algorithm for obstacle avoidance that works with Arduino thanks for your help in advance

The algorithm mentioned in the blog uses a Fuzzy Logic Controller to perform obstacle avoidance. You can read up more on fuzzy logic here: https://www.calvin.edu/~pribeiro/othrlnks/Fuzzy/home.htm

  newMotorSPD_L = basicVelocity + urgMotor_L + (urgTurn_R/4) - (urgTurn_L/2) + 60;
  newMotorSPD_R = basicVelocity + urgMotor_R + (urgTurn_L/4) - (urgTurn_R/2) + 60;

Based on the code, the formula is basically made up of variables with different weight/ratio.

basicVelocity is the default moving velocity of the robot when there is no obstacle or wall detected.

urgMotor_L/urgMotor_R is the ouput of the controller for frontal object detection/avoidance by getting the difference between the left and right ultrasonic sensor.

(urgTurn_R/4) - (urgTurn_L/2) is probably the left/right bias?

+60 at the end is probably to offset the error of the motor. (Assuming all other variable are 0, the robot should be still at 60 for their case?)

To simplify what the formula does, it can be shown using this graph:


Discrete H-Bridge very low current output I have built two parallel H-bridges from "Design 1" on this page as you can see in the attached schematic.

However when I apply the external power (VCC1 in the center of the diagram) the two motors do not spin.

Using my multimeter, I can see that the entire circuit is working: the motor is getting a 'forward' and 'backward' current as the Arduino sets the pins high. The multimeter is reading +/- 5.54V with the motor replaced by the multimeter. (Across the motor this drops to 0.13V)

So then I measure the current by putting my multimeter both in series with the motors and replacing the motors. There's only 40mA available! Looking around the web I found the suggestion to reduce the 220Ω resistors at R2, R3, R5 and R6. So I switched in (randomly) 27Ω resistors and the output current is still only 40mA.

What else should I try to bring up the current enough to drive the motors?

Edit: So my uneducated guess is that it's likely that the limitation is coming from the transistors. The Ns are BC549 and the Ps are BC559. The datasheets list "low current" as a feature, but I figured that was the collector.

Edit 2: The motor is this one which requires 70mA when running (and presumably more during startup)

Edit 3: Code driving the Arduino:

// Pin setup
int pinLeftMotorFwd   = 5;
int pinLeftMotorBck   = 6;
int pinRightMotorFwd  = 10;
int pinRightMotorBck  = 11;

// Directions for the {left, right} motors to achieve the four directions
int FORWARD[]   = {  1,  1 };
int BACKWARD[]  = { -1, -1 };
int RIGHT[]     = { -1,  1 };
int LEFT[]      = {  1, -1 };

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

    pinMode(pinLeftMotorFwd,  OUTPUT);
    pinMode(pinLeftMotorBck,  OUTPUT);
    pinMode(pinRightMotorFwd, OUTPUT);
    pinMode(pinRightMotorBck, OUTPUT);
}

void loop() {
    go( FORWARD, 10 );
    go( RIGHT,    3 );
    go( FORWARD, 10 );
    go( LEFT,     6 );
}

// Move the bot in a particular direction from the array above for a given number of seconds
void go ( int dir[], int dur ){
    leftMotor(  dir[0] );
    rightMotor( dir[1] );
    delay( dur * 1000 );
}

// Sill both motors (OK, so stop both motors. But stop is a keyword in C)
void still(){
    leftMotor(  0 );
    rightMotor( 0 );
}

// Set the left motor to Backward (-1), Forward (1), or Stop (0)
void leftMotor( int dir ){
    // Pull both pins low
    digitalWrite(pinLeftMotorFwd, LOW );
    Serial.println("pinLeftMotorFwd LOW");
    digitalWrite(pinLeftMotorBck, LOW );
    Serial.println("pinLeftMotorBck LOW");

    // If we're going forward, pull the Fwd pin high
    if( dir == 1 ){
        digitalWrite(pinLeftMotorFwd, HIGH);
        Serial.println("pinLeftMotorFwd HIGH");
    }

    // otherwise, pull the Bck pin high
    else if( dir == -1 ) {
        digitalWrite(pinLeftMotorBck, HIGH);
        Serial.println("pinLeftMotorBck HIGH");
    }
}

// Set the right motor to Backward (-1), Forward (1), or Stop (0)
void rightMotor( int dir ){
    // Pull both pins low
    digitalWrite(pinRightMotorFwd, LOW );
    Serial.println("pinRightMotorFwd LOW");
    digitalWrite(pinRightMotorBck, LOW );
    Serial.println("pinRightMotorBck LOW");

    // If we're going forward, pull the Fwd pin high
    if( dir == 1 ){
        digitalWrite(pinRightMotorFwd, HIGH);
        Serial.println("pinRightMotorFwd HIGH");
    }

    // otherwise, pull the Bck pin high
    else if( dir == -1 ) {
        digitalWrite(pinRightMotorBck, HIGH);
        Serial.println("pinRightMotorBck HIGH");
    }
}

Design 1 wouldn't be my first thought on how to do this either! The transistors aren't a great choice, but are cheap & common.

The layout here is more conventional, and you can physically link 1-2, & 3-4 to connect to your arduino without the risk of short circuits.

I suspect your code may be setting both lines high together - the only advantage I can see to the posted circuit is that this does not necessarily cause smoke (but may well do as you describe). This is why posting the code is recommended!


How to execute commands on Arduino (via PC) without touching the current sketch? I am working on my first Arduino project. It's a Reverse Geocache. Basically, it's a puzzle where a battery-powered Arduino is mounted inside a locked box, and is able to unlock the box if the user brings the box to the correct GPS coordinates and presses a push-button (that activates the Arduino, that runs a sketch, that checks the GPS, and operates a servo to release the lock).

It's all working, but I am trying to build in a backdoor, so I can unlock the box when I need to.

I have made the Arduino USB port accessible, and my hope is that I could connect a PC, and execute the appropriate command to operate the servo to unlock the box. The command is:

servo.write(OPEN_ANGLE);

The sketch that drives the whole puzzle depends on these libraries, but I am guessing the only one needed to operate the servo is PWMServo.h:

#include <PWMServo.h>
#include <SoftwareSerial.h>
#include <TinyGPS.h>
#include <EEPROM.h>
#include <LiquidCrystal.h>

I would like to be able to operate the servo without altering/replacing the uploaded sketch.

Is it possible to execute code "command prompt" style? Or can I somehow detect from within the sketch code that there is a USB connection, and have that trigger the unlock?

Finally (not the main question, but I would appreciate clarification), I have been told that the power to the Arduino should be disconnected before uploading new sketches (not sure why or if this is true). If forcing an unlock via the backdoor required uploading a new sketch, I seem to have a problem... For the puzzle to work within the locked box, the battery must be permanently connected, and also connecting to a PC via the USB seems to immediately power up the Arduino too. Does this mean uploading a new sketch would be impossible?

The simple thing would be for your sketch to read from the serial port continuously. If it finds something it stores it and when a newline arrives it sees if that happens to be a password known only to you. So, for example, all you would have to do is plug in the USB cable, activate the Serial Monitor on your PC, type swordfish and the servo opens the box.

You would need to allow for garbage arriving, so make sure that you discard input if it exceeds the size of the buffer you allocate for this purpose.

  I have been told that the power to the Arduino should be disconnected before uploading new sketches (not sure why or if this is true).

I don't see how that can be true as you have to reapply power to upload the sketch. I never do that.

  Is it possible to execute code "command prompt" style?

No, you upload compiled code.

  Or can I somehow detect from within the sketch code that there is a USB connection, and have that trigger the unlock?

Then all the person you give the box to has to notice the USB port, plug something in, and it unlocks. I think not.

An even simpler solution would be to have two locations that unlock the box. For example, your kitchen could be one, so to unlock it you just take the box to your kitchen. The other location would be the "real" one that you want your friend to have to find. All the stuff about "you are 200 km from your destination" would of course refer to the real destination. You just make the code check that if it happens to find itself in your kitchen it unlocks the box.


Can I connect and control 12 Arduino's over USB/serial to my laptop? I have 12 arduinos, each of them controlling some simple hardware peripherals. I want to interact with all of them over 1 USB connection to my laptop, where I have a python program communicating over serial.

The following seems like it could work: https://www.amazon.ca/Satechi-Power-Adapter-Control-Switches/dp/B0051PGX2I

Are there any electrical/other considerations to take into account for why this would/wouldn't work?

From a technical standpoint, USB can host up to 127 devices, so 12 Arduino boards is certainly not pushing the limit. Having 12 serial ports shouldn't be an issue in either Linux or Windows.

From a practical standpoint, you will have to find a powered USB hub which can support that many devices, or plug multiple hubs together. I'll leave that up to you as shopping recommendations are off topic.

In terms of the hub you use, you need to make sure you don't exceed its maximum current rating. The Arduino boards draw typically around 60-100mA alone. 12 of those and you will need at least 1.2A rating. The hub you mentioned says that it cannot exceed 2A. Depending on what other circuitry you attach to your Arduino boards you may need an external power supply for the boards.


Motor Shield and HC-06 Bluetooth Module competing for pins So my problem is this, I have an Arduino Uno with an Adafruit Motor Shield (1.0) and an HC-06 Bluetooth Module and I want to use them at the same time, the problem is that the Motor Shield uses all the ports that I need for the HC-06 (TX, RX, GND and VCC). In addition to all that, my project needs to be light weight (It's a quadcopter). Is there any way that I could use both of them at the same time?

Thanks in advance!

The motor shield doesn't actually use the TX and RX pins. Though as a shield it will go into all the arduino pins.

You could either solder some wires to the TX and RX pins, or use something like the proto shield to sandwich in the middle of it, and connect the BT module onto this shield.

You could also remove all the male headers from the motor shield, and replace them with stacking headers


When GPS can't see satellites, how can I continue to tick off a smooth-ish time? I'm getting 10 updates/sec from my GPS unit (The MTK3339 used in the Adafruit breakout board), and using it to update a clock display. This works well enough, though there's one minor problem that I'd like to solve and one major one that I have to solve.

The minor issue first; I don't get an update every 100ms. I get one roughly every 100ms... plus or minus about 20-30ms. If a late and an early update arrive back-to-back right when the display goes from n to n+1 seconds, it's noticeable that it's not ticking at a regular cadence. It's not fatal, but the arythmic stutter of it is deeply painful to watch.

The major issue is - what do I do when the GPS can't find a signal? Maybe the device is driving through a tunnel for a minute or there's some other sky obstruction. I still want the clock to update in a best-guess sort of way.

You can't just update the seconds display and then, 1000 (arduino-measured) milliseconds later, update the clock if a new message hasn't arrived. 1000 real-world milliseconds can be anywhere from 700 - 1400ms measured by an arduino, depending on the board and the quality of the crystal. Worse yet, the discrepancy is far from consistent within a single crystal. Seeing the processor speed up and slow down by several percent over the course of a few minutes isn't uncommon.

So what I'd like is a mechanism that will constantly smooth the received (GPS) time to give a best-estimate of current actual time. I'm okay with it being a second or two off (at most) from real time, as long as the cadence feels like actual seconds, and a loss of GPS for a few minutes can be quickly corrected when the signal is re-acquired.

I'm somewhat aware of (strikethrough)DIP(/strikethrough) PID methods, but I'm not sure how to apply them here. It seems that someone must have solved the problem for the sake of syncing internet time, so I shouldn't be reinventing a solution.

What you want, namely something to “smooth the received (GPS) time”,
is called a GPS disciplined oscillator. Obviously, you are not
after the high accuracy of commercial GPSDOs, but the working principle
of what you are describing is essentially the same.

  what do I do when the GPS can't find a signal?

In GPSDO lingo, this is called the “holdover” state. At this point you
rely solely on your local oscillator (here, millis() or micros()),
and steer it to correct for is natural drift, as determined while the
GPS reception was good. Or you can go fancy, measure the chip
temperature, and apply a temperature compensation.

  I'm somewhat aware of DIP methods, but I'm not sure how to apply them
  here

I guess you mean “PID”.

You apply this to the phase of the oscillator. If the local oscillator
is ahead of the GPS (positive phase error), you lower its frequency. For
example, you could increment the seconds count every 1,000,100
microseconds (as measured by micros()), instead of every 1,000,000.
This will make your clock a little bit slow, and resynchronize it with
the GPS. Conversely, if your clock is behind the GPS, you slightly
increase its frequency to make it run faster.

In other words, the error value of your PID is the phase error of your
clock, and the control variable is the frequency adjustment. By
applying the PID technique this way, you are building what is known as a
phase-locked loop, or PLL. This is the standard way of
implementing a GPSDO.

  It seems that someone must have solved the problem for the sake of
  syncing internet time

Sure, but NTP implementations can be quite complex, as they have to deal
with multiple servers having different round-trip delays and different
levels of trust. I am not aware of any Arduino library that does
anything similar. You may search for “time synchronization” or “PLL”. If
you don't find any, you can pick a PID library and apply it to your
oscillator.

A couple of final remarks:

You wrote “speed up and slow down by several percent over the course
of a few minutes isn't uncommon”. This shows there is something
awfully wrong with either your Arduino or your code. Over a few
minutes, you expect frequency variations of the order of one part
per million on an Arduino clocked off a ceramic resonator, and a few
parts per billion if yours is clocked off a crystal. See this
experimental study on the stability of an Arduino clock.
This stability problem is the very first thing you should investigate
and fix.
Many GPS modules have the option to give you a 1PPS (one pulse per
second) signal. If you can use this signal, you may get a quite
accurate measurement of your phase error. Relying on the NMEA
sentences will give you lots of jitter, which you would then have to
compensate for by setting the time constant of the PLL to a very long
value.


Help with placing a function please I am trying to call a function that will turn a stepper motor a number of steps depending on the value submitted through the serial console. For an example, if I submit 50, the motor should turn 50 steps clockwise (and counter clockwise for  a negative value).

#include <Stepper.h>
#define STEPS 200
Stepper stepper(STEPS, 8, 9, 10, 11);

int serial_input = Serial.read();

void setup() {
Serial.begin(9600) ;
stepper.setSpeed(30);
}

void loop() {
}

void turnMotor(serial_input){
  stepper.step ( serial_input ) ;
}

And here are the errors I get:

Motor4.ino:12:28: error: variable or field ‘turnMotor’ declared void
Motor4.ino:12:16: error: ‘serial_input’ was not declared in this scope
Motor4.ino:117:28: error: variable or field ‘turnMotor’ declared void

Thank you

As Juraj already explained, you cannot use Serial.read() outside a function.

What you probably want is to call it within the loop, or a function called from loop (via other functions).
Than you can call also turnMotor from Loop or a function called from loop. The value (int serial_input) probably doesn't have to be global anymore, but that depends on the time where you assign the value and where you call turnMotor.


Interfacing 9-Axes Motion Shield with RPi and WiFi Shield I recently purchased the Arduino 9-Axes Motion Shield. I have two questions:

Q1. The official Arduino page says that the shield doesn't have any external power source and can only be powered up by stacking on top of an Arduino board. How can I use this shield with a Raspberry Pi?

Q2. A page here shows that it has support for the Ethernet Shield but doesn't mention WiFi shield anywhere. Does this mean that I cannot use my WiFi shield with it? I plan to stack the 9-axes shield on top of the WiFi shield which in turn is stacked over Arduino Uno.

Q1. The official Arduino page says that the shield doesn't have any external power source and can only be powered up by stacking on top of an Arduino board. How can I use this shield with a Raspberry Pi?

By providing the right power to the right pins.

  Q2. A page here shows that it has support for the Ethernet Shield but doesn't mention WiFi shield anywhere. Does this mean that I cannot use my WiFi shield with it? I plan to stack the 9-axes shield on top of the WiFi shield which in turn is stacked over Arduino Uno.

No, it says it is compatible with the Arduino Ethernet which is not a shield, it is an Arduino.

What other shields you can use it with depends on what pins those other shields use.  Look at the schematics. Read the manuals. Do some leg-work.


Help connecting ILI9341 LCD SPI Display to arduino uno I got this lcd with touchscreen from a store but i have no idea on how to connect it to the arduino uno.
Any help is appreciated.

This is where i bought it from.

The display

My Arduino

You can get it working by two methods

using a voltage divider e.g to shift from 5V to 3.3V you could use two resistors, 100k and 200k respecfully and between both resistors there is voltage of 3.3. One for each pin that needs it.
Using 10K resistors in series between the LCD and the arduino. I really don't know how is working but it works fine that way.

I tested both methods, also the MISO pin from the LCD can be connected directly to your arduino.


Data logging speed with arduino I am trying to make some data logging conserining physiological data coming from a bitalino.
My problem is that I would like to collect samples at something like 1 kHz, that is the rate that the bitalino can read the sensors, but I think that the time needed
to write this data to the SD card can't keep up with the speed, and here is why i think that:

I put in the script some timers to check what was consuming the time causing to low sample rate, resulting:

Bitalino: 0, SD: 27
Bitalino: 0, SD: 28
Bitalino: 2, SD: 26
Bitalino: 0, SD: 29

Being that the time in miliseconds.

void loop() {
    time = millis();
    readBIT();
    time2 = millis();
    printDataSD();
    time3 = millis();
    printData();
}

void printData() //Send the data acquired to the pc through the serial port
{
  Serial.print("Bitalino: ");
  Serial.print(time2-time);
  Serial.print(", SD: ");
  Serial.println(time3-time2);
}

void printDataSD() //Send the data acquired to the SD Card
{
    if (myFile) {
    //Bitalino
    myFile.print(_ECG);
    myFile.print(",");
    myFile.print(_EMG);
    myFile.print(",");
    myFile.print(_EEG);
    myFile.print(",");
    myFile.print(_EDA);
    myFile.print(",");
    //Time
    myFile.println(time);
    myFile.flush();

    } else {
    Serial.print("error opening file, ");
    SD.begin(10);
    delay(1000);
  }
}

I would like to know if there is a way to improve my sample rate.

Thank you!

Here is the readBit() like asked:

void readBIT() //Read IMU data
 {
  _ECG = analogRead(ECG);
  _ECG = ((_ECG/1024) - 0.5)*Vcc*1000/gECG; //mV

 _EMG = analogRead(EMG);
 _EMG = ((_EMG/1024) - 0.5)*Vcc*1000/gEMG; //mV

 _EEG = analogRead(EEG);
 _EEG = ((_EEG/1024) - 0.5)*Vcc*1000000/gEEG; //uV

 _EDA = analogRead(EDA);
 _EDA = (_EDA/1024*Vcc-0.259388)/gEDA; // revolution
 }

The OP has likely solved this problem by now, but I know that others will be in the same position, so I am answering for them.

I routinely record ten channels of biological sensors including one of 16-bit sound at 8 kHz (plus the associated FFT data) to an SD card using arduino-compatible systems, so I doubt very much that the SD card writing per se is the problem.

Throughput to an SD card is a function of several variables.

To maximize write throughput you need to write full blocks of data at
the correct block size, since partial blocks take the same amount of
time as full blocks.
You also need to be ready with more data as soon as the SD card is
ready to take more, otherwise precious cycles slip away from you.
You need to ensure that your writes are non-blocking (don't try to
write more than the buffer can receive) so your loop can process and
queue up new data while the SD card is doing its thing.
You need to read any timing-sensitive sensors using interrupt service
routines that write their data either to a circular buffer or to one
of a group of two or three buffers that are cycled between being
filled and being emptied.

Printing debug statements to the serial port can take many tens of milliseconds in a loop that otherwise may take only a few microseconds. If you write more than the serial port buffer can hold, the call will be blocking and you will be at the mercy of the PC that's reading the serial port. This will always be bad enough to mess up the program you're trying to debug... I've encountered situations where this introduced delays of up to 10 seconds (the PC was misbehaving, but still...).

A quick improvement to printing debug statements is to maintain a loop counter and only print a debug statement every N loops.

The program in the original question uses a naive strategy in the sense that it acquires some amount of data and then immediately tries to write it to the SD card, waiting until the write is complete before trying to acquire new data. This will never work at high data rates for the reasons given above. If you use this approach, you are likely wasting 90% of your program cycles in waiting for the SD write and the Serial port write. If either one takes too long, you will miss the next data acquisition window.

My advice: your first step is to research and find or write a circular buffer library.

Then set a timer to call an interrupt service routine that acquires data and puts it into the circular buffer.

Write a loop routine that checks to see whether the SD card is available for writing, and then takes just enough data out of the circular buffer to fit in a single block write for your SD card (look at the documentation for the card adaptor and the card).

At that point you will know whether your system can keep up with your needs.

It's possible that your SD card writing itself is OK but your Arduino is having trouble keeping up either because it's too slow or because you don't have enough room for a sufficiently large circular buffer. I doubt this because I've recorded and played back audio at 8 KHz on the Uno, but then I don't know what else you need to accomplish in your program.

If you do determine that the Arduino itself is too slow or has insufficient memory, take a look at the Teensy series of boards [https://www.pjrc.com/teensy/index.html]. They are entirely compatible with Arduino libraries and IDE but they run hundreds of times faster than the Uno at a larger data width, plus they have oodles of RAM and a gazillion pins. They're also much smaller than the Arduino form factor and the community that uses them is very knowledgeable.

If it turns out that SD card write throughput is OK but that it requires more buffering than you have on-board, you can add an SPI ram breakout board for more fast buffering space.

Finally, if the amount of data you need to collect is so large and so continuous that you simply can't buffer it long enough to get it written out to SD, or if the SD card truly can't keep up, or if the data is larger than any available SD card, you may consider sending your data off the board in near-real-time. I send 10 hours of nightly data from a Teensy over a USB virtual serial port to the PC at about 3Mbps, and others have done better. Ethernet output is also available and can be at least an order of magnitude greater.

glhf!


Esp8266 firmware update with uno "chip sync error" I have an ESP8266-01. I followed the instructions on this

http://yaab-arduino.blogspot.com/2015/12/flashing-esp8266-firmware-arduino.html?m=1

exactly. When I start the firmware update the TX and RX pins blink rapidly along with the blue light on the ESP.

Then the terminal spits out "chip sync error" and disconnects.

I would like this to work because buying a ftdi cable isn't an option right now.

I run the same problem too and took me countless hours to figure this error out. The problem seems the Baud rate starts at 115200 while the COM port is set to 9600. What I did is I checked the Device Manager and find the COM port, right clicked to properties and to the Port Settings Tab, I changed the Baud Rate to 115200 and flash the firmware again. And it works!


NodeMCU power consumption measurement and DeepSleep I'm working on a project using a nodeMCU using a ICR14500(3.7V and 700mAh) battery and I'm experienced some issues when I try to estimate the total current consumption. Firstly I experienced some problems with the power supply (here is the previous question NodeMCU powered with battery and use WiFi) but this problem is now solved.

At this moment if I measure the current consumption connecting the amperimeter in serie between the battery and the nodeMCU input voltage pin I see a current consumption of 140mA continiously (ignoring the deep sleep mode) and I experienced some strange behaviours in my NodeMCU, even the code doesn't work. If I remove the amperimeter from my set up all works smooth and my source code works perfectly.

In order to validate my amperimeter I modified a usb cable and I added the amperimeter in the middle of the wire and I measured the current consumption powering me nodeMCU from the computer and I saw a current consumption of 80mA when the code is run and 14mA when the device is in deep sleep. This behaviour seems the expected one.

Are there any colateral effect measuring the battery current consumption which I haven't considered?

An ammeter is basically a small resistor in series over which the voltage drop is measured. That resistance will play a part in the effective output impedance of your power source (battery).

This increased impedance will reduce the overall amount of current the battery can provide before the voltage drops to an unacceptable level.

For instance, I just did a crude measurement of the resistor used for the 200mA range of one of my DMMs and came up with a value of 1.2Ω. At 140mA that would give a voltage drop of (V=IR = 0.14 × 1.2) 0.168V. That's 0.168V that your NodeMCU won't be seeing. Add to that the fact that the WiFi will be creating peaks of current usage up to, say, 500mA (probably less, that's just a wild guestimate), the voltage drop will increase to (0.5 × 1.2) 0.6V. From a battery giving 3.7V nominal that would plummet to 3.1V as seen by the NodeMCU.

Depending on what kind of power regulation you are using that will most likely cause brown-outs of the power and the MCU will reset or crash.

When powered by 5V that 0.6V drop would not be as noticeable, since 4.1V is still well above what is needed to power the chip and the voltage regulation can still work properly.

So how can you measure the current with the battery? Well, there's two options:

Use a much smaller resistance (0.1Ω, for example) and measure the voltage across it - then use Ohm's Law to calculate the current.
Add a large electrolytic capacitor to the input of the NodeMCU after your current measurement to act as an energy source for sustaining the peaks of current required by the WiFi. By big I mean something like 3300µF:

simulate this circuit – Schematic created using CircuitLab


How to learn electronics/programming with Arduino? I want to learn core and mechanics of microcontrollers with Arduino, and I don't really know where to find good source of knowledge.

Every Arduino related tutorial is about very basic stuff like connecting the LCD display without explaining what every pin does. When it comes to programming tutorials only explain what functions are needed and do not explain what happens inside the hardware.

For example i know what delay() function does, and I know that I can find definition in the source files:

void delay(unsigned long ms)
{
    uint16_t start = (uint16_t)micros();

    while (ms > 0) {
        yield();
        if (((uint16_t)micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

But what I really want to know what that code does, and how to write own functions. I would appreciate if you could provide me with any starting point. Should I just follow the source files until I get it or is there any better reference?

I have Arduino Leonardo, and experience in programming in C/C++.

There are two main topics there: Digital Electronics, and C++ programming, and the Arduino happens to bridge the gap between the two.

That's why it's hard to find tutorials in the style you want.  So instead of looking for Arduino tutorials that do what you want you need to split the topics apart and deal with them separately.

Search for C++ programming tutorials. That should help you understand the structure and syntax of a program better. Search for digital electronics tutorials. Good keywords are things like logic gates, combinational logic or digital interfacing and just digital electronics. That should help you understand things like logic levels, logical functions, inputs and outputs, and such like.

Once you have basic understanding in both fields you can begin to see how the two relate together. One of the most important skills any engineer has is understanding and interpreting datasheets. From datasheets you can find how the hardware operates and what you would need your program to do to make the hardware do what you want.


What is the name of this chip on Arduino Mega ? I am not finding its datasheet 56 TI MSP? What is the using purpose of this chip?

There is only one 8-pin SMD IC on the top side of the Arduino Mega 2560.

From the schematic
it appears to be the "LMV358IDGKR" a TI dual op-amp used for two separate functions on the Mega.

Selecting power source - VIN vs USB.
Illuminating the built-in "L" LED (on D13) without loading PB7


Program Arduino via UART from ESP8266 SPIFFS I have built a custom board that has an ATmega328p connected to an ESP8266 module via UART. I am currently programming the ATmega328p using a USBtiny programmer via an SPI header. The ESP8266 module is programmed via an FTDI cable connected the the UART.

Firmware for both are created in Arduino IDE.

I have set up a webserver on the ESP that allows for files to be uploaded to the SPIFFS via FTP. I would like to be able to upload a hex file for the ATmega and then have the ESP program the ATmega via the UART connection. A GPIO on the ESP controls a transistor that can pull the reset pin on the ATmega to ground.

I know I need a bootloader on the ATmega (e.g. optiboot), but I don't know what I need to make the ESP do to trigger the bootloader and flash the ATmega. I'm thinking I need something like:

void initialiseAtmegaFlash () {
  // Trigger the bootloader to accept incoming hex over UART
}

void flashHexToAtmega (File atmegaHex) {
  for (uint32_t i = 0; i < atmegaHex.size(); ++i) {
    // Handle timing of sending byte by byte over serial... or chunk by chunk?
  }
}

To answer my own question in case someone else ends up here, the library Juraj suggested (https://github.com/ciminaghi/libdfu) looks like it does the job. I also found another project doing something similar (https://github.com/rene-win/esp_avr_programmer). Also the STK500 docs linked to by Majenko (http://ww1.microchip.com/downloads/en/AppNotes/doc2591.pdf) are really useful for understanding the nuts and bolts!


Arduino based SPI programming of LT1257 not working I am trying to talk to an LT1257 using an Arduino Nano Atmega328. I am not using the default slave select pin. I am using pin 5 as chip select for the DAC. The LT1257 data sheet shows this timing diagram. What I inferred from this diagram is that SCLK can be used to clock in the data and it remains in the shift register and is loaded into the DAC register only when Load is pulled low.

I wrote this snippet to load a 0x0000 to the DAC. However, when I probe the output voltage it is ~1.02V. The DAC uses an internal reference of 2.048V. So I think this must be the default 1/2*FS output when the DAC powers on.
Please review my code and point the errors. (At the DAC output I have a 1k resistor connected to ground).

#include<SPI.h>
#define SCLK 13
#define MISO 12
#define MOSI 11
#define DAC_LOAD 5

#define DAC_SPI_CLOCK_SPEED 1000000 //Upto 1.4MHz

void setup()
{
Serial.begin(9600);
init();
SPI.begin();
dac_write();
}

void init()
{
pinMode(SCLK, OUTPUT);
pinMode(MOSI, OUTPUT);
pinMode(MISO, INPUT);
pinMode(DAC_LOAD, OUTPUT);
digitalWrite(SCLK, HIGH);
digitalWrite(MOSI, HIGH);
digitalWrite(DAC_LOAD, HIGH);
}

void dac_write()
{
SPI.beginTransaction(SPISettings(DAC_SPI_CLOCK_SPEED, MSBFIRST, SPI_MODE0));
delay(10);
SPI.transfer(0x0000);
delay(10);
digitalWrite(DAC_LOAD, LOW);
delay(10);
digitalWrite(DAC_LOAD, HIGH);
delay(10);
SPI.endTransaction();
}

void loop()
{
while(1)
{
Serial.println("Ping!");
delay(1000);
}
}

I read the LT1257 data-sheet more carefully. There is a pull down nmos at the output of the DAC. So when uninitialized, the output of LT1257 should be ~0V. So the output I was measuring (~1.02V) is spurious. I suspect I damaged the IC. I tried the same code on a different LT1257 and it worked. I can confirm now that this code is working.


Function that returns a Structure I want to create a structure called CarSpeed it has 4 int FR,FL,BR,BL (FrontRight,..) ; and i would like to create a function that returns this structure :

ActualSpeed Readspeed(void)
{
   code to read the speed of the car(already done)
}

Can someone help me define a function that returns this structure  ? only the way how I should define it, the usual C way doesnt work :

typedefstruct CarSpeed{...}

and then

CarSpeed ActualSpeed;
ActualSpeed Readspeed(void){.. }

Since you're (probably) using a C++ compiler, it's usually easier to declare structures like this:

struct CarSpeed
{
    int fr, fl, br, bl;
};

(Note that there's no need for typedef.)

You can then return an instance of it directly from your function:

CarSpeed ReadSpeed()
{
    CarSpeed data;

    data.fr = ...;
    data.fl = ...;
    data.br = ...;
    data.bl = ...;

    return data;
}

You can call it from another function like this:

CarSpeed speed = ReadSpeed();

That will copy the contents of the structure into an object called speed. In this example, it's an 8 byte structure so it's a non-trivial copy. That shouldn't be a big problem unless you're calling it very frequently though.

As noted in another answer, using a pointer (or a reference) can be more efficient if necessary.


How to power up this LCD 7 segments display I got two of these type of 7 segments display in LCD material.

And here is the datasheet

I tried to power up to UNO, it can make the segment on, while a second, the segment go off, but the pinMode does not changed.

that's a controller-less dynamic (mutiplexed) display, with 4 coms.

So you will to program the mcu to do a lot:

1) the com pins are driven with 1/4 dc signal sequentially;

2) the seg pins are driven with 1/3 bias voltage. out-of-phase to be dark and in-phase to be transparent (not lit).

the way to do it is to:

put segment info in a buffer;
write a display update routine that scans digits and updates the com/seg pins according to the current digit's segment information;
call that display update routine periodically, preferrably from a timer isr.

the display update routine would be similar to an led display routine - an example of that (for led) would be here (https://dannyelectronics.wordpress.com/2017/06/30/a-more-flexible-driver-for-7-segment-leds/), but more complex due to the 4 com pins and bias generation.

it is much easier to pick a mcu with built-in lcd driver and program that mcu as a display controller / slave taking in information from a master (in this case your arduino).


Arduino Nano stucks on uploading I'm trying to upload an simple blink sketch to my Arduino Nano, which not used for a while.
As I remember, I uploaded an sketch to control RF module, at the last time I used. Now, when I connect my Arduino Nano, I 'm getting error message every second, from my serial monitor saying the the RF communication cant start, because I have disconnected all connections to the RF module.
It seems the Nano is working, and the Nano driver is working properly. I tried resetting manually, and uploading many times with random timings. But up to now, the sketch not uploaded, and waiting. When I press reset button while uploading, Arduino shows me the error it cant communicate.
I think the Arduino IDE not getting enough time to upload from serial, because it's busy all the time.
Is there any way to wipe out the existing sketch from Nano? or any working solution to upload my new empty sketch or simple blink sample? It's a big help if anyone can shed me some light to make my Nano work again.

I have solved the issue by selecting,
Tools > Processor > ATMega (Old bootloader)
@Juraj, Thank you for suggestion.


Observing USB Gamepad with Arduino? I have a gamepad which I want to treat as a sensor for my Arduino board. I want Arduino to trigger a certain action based on button pushes from the gamepad. Different buttons, different actions.

The gamepad comes with a USB connector. I cut the the USB cable open, solder it with pluggable pins which are then connected to a breadboard. I supply the gamepad with 5V power from Arduino and connect the USB's Data+ to Arduino's analog input pin (A0). Please check the images below.

I thought by observing the voltage coming from the gamepad's Data+ pin, I can probably determine if a button is being pushed. However, the observable input voltage in Arduino's A0 do not produce any meaningful difference between button push and release.

My question: Is it possible to detect Gamepad's button pushes with this arrangement? If it's possible, where do you think I'm doing wrong?

simulate this circuit – Schematic created using CircuitLab

As mentioned, the problem is the gamepad you have uses communicates over USB, which requires a USB Host chip to communicate with. However, USB Host shields can be found on eBay (under "arduino USB Host shield") from US$10, and they come with a USB socket, so you could use it easily with another gamepad that hadn't had the connector snipped. This also would allow use with HID devices such as mice and keyboards if you wished, so a worthwhile shield to own.


Problem on multiple interrupts operation on Arduino Uno I experimenting with the interrupt ISR using Arduino Uno. In my circuit, I am taking two switches which are connected with Uno's interrupt pins, pins 2 and 3, and also taking multiple LEDs which are connected with other pins.

My logic is when I press switch1 (which is connected to pin 3) LEDs should be turned on by the interrupt service routine and when I press switch2 (which is connected to pin 2) LEDs should be turned off by the interrupt service routine.

My problem is that when I pressed switch1 LEDs are turned on but when I pressed switch2 LEDs are not turned off.

Here's my code:

int switch1 = 3;
int switch2 = 2;
int led1 = 13;
int led2 = 12;
int led3 = 11;
int led4 = 10;
int led5 = 9;
int led6 = 8;
int led7 = 7;
volatile bool flag1 = false;
volatile bool flag2 = false;
//volatile byte state = LOW;

void setup()
{
  pinMode(switch1, INPUT_PULLUP);
  pinMode(switch2, INPUT_PULLUP);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);
  pinMode(led6, OUTPUT);
  pinMode(led7, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(switch1), &setFlag1, CHANGE);
  attachInterrupt(digitalPinToInterrupt(switch2), &setFlag2, CHANGE);
}

void loop()
{
  if (flag1)
  {
    off();
  }
  if (flag2)
  {
    blink1();
  }

}

void blink1()
{
  attachInterrupt(digitalPinToInterrupt(switch2), setFlag2, CHANGE);
  digitalWrite(led1, HIGH);
  blink2();
}

void blink2()
{
  digitalWrite(led2, HIGH);
  blink3();
}

void blink3()
{
  digitalWrite(led3, HIGH);
  blink4();
}

void blink4()
{
  digitalWrite(led4, HIGH);
  blink5();
}

void blink5()
{
  while (1)
  {
    digitalWrite(led5, HIGH);
    delay(10);
    digitalWrite(led5, LOW);
    delay(10);
  }
}

void off()
{
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  digitalWrite(led3, LOW);
  digitalWrite(led4, LOW);
  digitalWrite(led5, LOW);
  attachInterrupt(digitalPinToInterrupt(switch1), setFlag1, CHANGE);
}

void setFlag1()
{
  detachInterrupt(digitalPinToInterrupt(switch1));
  flag1 = true;
}

void setFlag2()
{
  detachInterrupt(digitalPinToInterrupt(switch2));
  flag2 = true;
}

You are being way way too convoluted with this. You're overthinking it.

The code should be as simple as (LED stuff omitted):

volatile bool running = false;
const uint8_t switch1 =3;
const uint8_t switch2 =2;

void setup() {
    pinMode(switch1, INPUT_PULLUP);
    pinMode(switch2, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(switch1), turnOn, FALLING);
    attachInterrupt(digitalPinToInterrupt(switch2), turnOff, FALLING);
}

void loop() {
    if (running) {
        // Do something
    } else {
        // Do something else
    }
}

void turnOn() {
    running = true;
}

void turnOff() {
    running = false;
}

Note that what goes in loop() should be non-blocking, or at least have a reasonably short duration, so that it is able to pick up the changed running variable.

However, for something like this, interrupts are pretty pointless.


Can't Upload Sketches to Arduino Nano Every first-time builder here.  I just got my Arduino Nano Every in the mail from Mouser, and I'm trying to upload a modified version of the blink example to my new brand-new board.  However, every time I try to upload a sketch, the IDE just spins its wheels for around 5 minutes before giving up.  I've been trying to look through similar questions and haven't found anything that has solved my issue.  My OS is Windows 10.
Here's a snippet of the log (I've turned on verbose reporting for compilation and upload):
Arduino: 1.8.13 (Windows 10), Board: "Arduino Nano Every, None (ATMEGA4809)"
…
Forcing reset using 1200bps open/close on port COM1
…
         Using Port                    : COM1
         Using Programmer              : jtag2updi
         Overriding Baud Rate          : 115200
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
avrdude: jtagmkII_getsync(): sign-on command: status -1
An error occurred while uploading the sketch

Here are the settings I'm currently using:

Board is set to Arduino Nano Every, using Arduino MegaAVR Boards
1.8.6
Registers emulation:  none (ATMEGA4809)
Port:  COM1 (there are no other options that appear for me, and no
other port pops up in the device manager when I plug the board in)
Programmer:  Onboard Atmel    mEDBG (UNO WiFi Rev2)

Here's what I've tried so far:

Disabled antivirus
Uninstalled and reinstalled Arduino IDE
Turning on registers emulation
Restarting computer
Resetting board
Using different USB cables
Using different USB ports (3.0 and 2.0)
Manually installing Arduino drivers to Windows (Windows said the most
up-to-date drivers were already installed after I specified the
directory to search in)
Nothing is connected to the board.
The pin-13 LED blinks, so there's a bootloader on the board.
I've reset the board before uploading.

Any help would be very much appreciated.  I'm about to give up and just return the board and swap it for a different one.

Here is a trick I use on some boards but first be the baud rate is the same in the terminal as in the sketch (Serial.begin(115200). If so then remove everything then put a jumper between ground and reset. Then put a jumper between TX and RX (pin o and pin 1 on uno). launch the IDE and what you type in the console should be echoed back to you. If this works the hardware is connected fine.


Arduino RS485 shield to RS485 temperature & humidity sensor I’m try to get data from rs485 is not work please advise to me.

1.  Try to connect PC usb485 to DY-MD02 is work.
    Send command “AUTO” or “READ”

2.  Try to Arduino rs485 shield to DY-MD02 is not work.
    Send command “AUTO”

my code

''''

char command[4] = {'A', 'U', 'T', 'O'};

int n = sizeof(command)/sizeof(command[0]);   // Number of elements in an array

String incoming = "";   // for incoming serial string data

void setup()

{

      // initialize serial ports
      Serial.begin(9600);
      pinMode(EN,OUTPUT);
      digitalWrite(EN,HIGH); //Enable high, RS485 shield waiting to transmit data
      Serial.write(command,n); //Test send command Auto,Read to RS485
      delay(500);
}

void loop()

{

      String temp;
      digitalWrite(EN,LOW); //Enable low, RS485 shield waiting to receive data

      while(Serial.available() > 0 )
      {
          temp=Serial.read();
          Serial.println(temp);
          delay(1000); //Delay for some time, waiting for data transmitted
      }

}

''''

if change code to = Serial.readString() not show anything.

please help me
Thank

to Juraj

Maker tell me can connect with Arduino uno and send manual to me.

see in attach file.

i'm tray change this code to readStringUntil, is OK

if(Serial.available() > 0)
  {
    temp = Serial.readStringUntil('\n');
    Serial.println(temp);
    delay(1000); //Delay for some time, waiting for data transmitted
  }

Thank all for help me
^^


that no matter what the inputs are Motor1 always moves int motor_forward1 = 7;
int motor_reverse1 = 6;
int motor_forward2 = 5;
int motor_reverse2 = 4;
int motor_forward3 = 3;
int motor_reverse3 = 2;
int sensor1 = A0;
int sensor2 = A1;

 void setup()
{

   pinMode(motor_forward1, OUTPUT);
   pinMode(motor_reverse1, OUTPUT);
   pinMode(motor_forward2, OUTPUT);
   pinMode(motor_reverse2, OUTPUT);
   pinMode(motor_forward3, OUTPUT);
   pinMode(motor_reverse3, OUTPUT);
   pinMode(sensor1, INPUT);
   pinMode(sensor2, INPUT);
 }

 void loop()
 {
   if (digitalRead(A0) == HIGH)
   {
     digitalWrite(motor_forward1,1);
     digitalWrite(motor_reverse1,0);
     delay(5000);
     digitalWrite(motor_forward1,0);
     digitalWrite(motor_reverse1,1);
     delay(5000);
     digitalWrite(motor_forward1,0);
     digitalWrite(motor_reverse1,0);
     delay(1000);
   }
   else if (digitalRead(A1) == HIGH)
   {
     digitalWrite(motor_forward2,1);
     digitalWrite(motor_reverse2,0);
     delay(5000);
     digitalWrite(motor_forward2,0);
     digitalWrite(motor_reverse2,1);
     delay(5000);
     digitalWrite(motor_forward2,0);
     digitalWrite(motor_reverse2,0);
     delay(1000);
   }
   else
   {
     digitalWrite(motor_forward3,1);
     digitalWrite(motor_reverse3,0);
     delay(5000);
     digitalWrite(motor_forward3,0);
     digitalWrite(motor_reverse3,1);
     delay(5000);
     digitalWrite(motor_forward3,0);
     digitalWrite(motor_reverse3,0);
     delay(1000);
   }
   delay(5000);
 }

Schematic here.

The code isn't wrong, it's far too simple to be at fault.

The error is from within Proteus. Those 'pushbutton' switches (and the other switch simulations) are not quite as straightforward as one would like. They have an OFF resistance, usually 100 Megaohms, but that's enough to trick the simulation into not behaving like it should do. You MUST pull the inputs to ground with a resistor - any sensible value will do as it's only required for the simulation. As they are, they're in some odd floating/magic/unknown state; common sense does not apply here!

An alternative is to swap the pushbutton for a SPDT switch; connect the common to the Arduino and the other contacts to the 7805 output and ground. You won't need the resistor in this case.


The Arduino Sketch does not save in Arduino folder location I have just installed Arduino on Mac OS. The Arduino folder is created under Documents. But whenever I save the sketch it gets stored in some ghost location and gives an error, the same name already exits. Upon finding the location of file. It gets stored under this directory(Hidden).

/private/var/folders/_v/nbrwcsh51wd2k07kfhy9vhjm0000gn/T/untitled1010592992.tmp/sketch_sep28a

How can I move this location to my documents folder. In Arduino preferences, I have also changed the location of sketch, still it does save in above location.

Download the latest IDE from Arduino.cc
Drag your Arduino application icon to the trash.
Open up terminal and type rm -r ~/Library/Arduino15
Delete the Arduino folder in your Documents folder for good measure
Drag the newly downloaded Arduino application to your application folder and see how it goes from a clean install.

Failing that PlatformIO IMO is a much better IDE for developing on these platforms : http://platformio.org/


Are there fixed connectors for gpio? Curently I am using these connectors for my prototype:
Ebay link

However, I need something more reliable so I can deliver the prototype to a user without to risk that the cables fall out of their pins.
Is there something else to use? I would like to avoid soldering.. :(

Unless you want to replace the headers with something else, which means soldering, then you will be soldering.

The options are:

Solder different connectors in the place of the existing headers
Remove the existing headers and solder wires directly in their place
Get a prototyping shield and solder wires in to that
Get a prototyping shield and solder different connectors to it.

Whatever you choose you will be soldering.

Don't be scared of soldering - it's the most basic thing you need to be able to do when you are working with electronics.


What are the 5V and VIN pins for? I believe I can supply the Arduino with power in three different ways:

Use USB. The design trusts the 5V to be regulated, and does not regulate it in any way.
Use a regulated power source, trusted to be 5V, and connect it to GND and 5V.
Connect an unregulated power source, eg a battery, to GND and VIN. This should be above 6.2V (since the dropout voltage is 1.2V) and preferably between 9V and 12V. There is a built-in regulator that will supply the Arduino with exactly 5V.

But can I use any of those pins to power other components. E.g. if the Arduino is powered with USB, can I use the 5V pin to power a diode? I thought I could, but the voltage is 4.70V, while the USB is 5.07V. The VIN is 4.26V btw.

Are the 5V and VIN only for powering the Arduino?

No. You can draw power from the 5v and VIN pins on the arduino. VIN is the completely unaltered input power before the regulator (it will be useless if regulated 5v is supplied directly). Outputting power is what the 5v pin is intended to be used for, not as a power input.

From the arduino website:

  5V. This pin outputs a regulated 5V from the regulator on the
  board. The board can be supplied with power either from the DC power
  jack (7 - 12V), the USB connector (5V), or the VIN pin of the board
  (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the
  regulator, and can damage your board. We don't advise it.


Cheap ATtiny programmer on Debian I've recently purchased a no-brand 1€ ATtiny programmer off eBay, and with the ridiculous price obviously came no documentation nor support from the seller.

At first I thought that using it with the Arduino IDE would have been as simple as plugging and programming, but no default lib worked. My hopes definitely crumbled when I realized the device wasn't even being picked up by Debian, showing instead this in the logs:

kernel.info: [ 2758.501968] usb 6-3: new low-speed USB device number 2 using ohci-pci
kernel.err: [ 2758.641798] usb 6-3: device descriptor read/64, error -62
kernel.err: [ 2758.885515] usb 6-3: device descriptor read/64, error -62
kernel.info: [ 2759.125231] usb 6-3: new low-speed USB device number 3 using ohci-pci
kernel.err: [ 2759.265065] usb 6-3: device descriptor read/64, error -62
kernel.err: [ 2759.508779] usb 6-3: device descriptor read/64, error -62
kernel.info: [ 2759.748500] usb 6-3: new low-speed USB device number 4 using ohci-pci
kernel.err: [ 2760.156027] usb 6-3: device not accepting address 4, error -62
kernel.info: [ 2760.291871] usb 6-3: new low-speed USB device number 5 using ohci-pci
kernel.err: [ 2760.699382] usb 6-3: device not accepting address 5, error -62
kernel.err: [ 2760.699421] usb usb6-port3: unable to enumerate USB device

and with lsusb outputting this:

Bus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 002 Device 003: ID 07d1:3c0a WiFi Dongle
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 003 Device 002: ID 045e:0745 Mouse/Keyboard BT Dongle
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

Reading up on the subject seemed to confirm that it was something I shouldn't have bought, and the closest I've got to a better understanding was with this question (link) which I can't comment.

So building up on the answer there, can anyone please explain a bit more in detail what for and where micronucleus would be needed?

Alternatively, is it possible to go with something as easy as installing the drivers and plugging it into the Arduino IDE?

Micronucleus is a bootloader - in the same way that Optiboot is a bootloader used on the Uno. It provides the USB connection to program the chip.

Without it you can't do anything at all with that, since the USB port just plugs direct into the ATTiny chip. With no software on the chip the USB port doesn't do anything.  It's kind of a catch-22 situation - you need software on the chip in order to put software on the chip.

In essence Micronucleus turns the ATTiny into a kind of Mini Leonardo.

You need to first put Micronucleus on the chip (which you can do with an Arduino as an ICSP programmer) and then once that is installed you should be able to start using that little board with the chip to program it.

Since you're on a decent operating system there's no need for "drivers".


Utilizing 3G/4G connection as gps Is it possible to get GPS data without using a GPS, but instead using the internet provided from a 3G or 4G connection to get GPS data?

Maybe if you used the HTML5 geolocation API somehow?

I have already used a GPS module together with a GSM modem, but i only used the GSM modem for SMS and not potential internet capabilities.

The beneftis from this , besides cost, would be a smaller program, intended for arduino nano, as TInyGPS and TinyGPS++ libraries are already big enough.

So my question really is twofold:
1. Is there any way to utilize the internet connection from GSM modems (besides the obvious SMS/call function)?
2. Is there a way to utilize the internet connection to get GPS data, without using an actual GPS module?

You cannot get GPS data without getting GPS data. That's like wanting to get milk from a cow without using a cow.

Some GSM modem modules also include a GPS chip. If yours does you can use that. If not then the closest you can get is:

Country (or maybe city) the IP address is registered in
Cell ID and location of the tower you are communicating with

Both of those are only very rough "somewhere within this square few miles" or "somewhere in this country" kind of data. Any more than that and you need GPS.

Mobile phones augment the GPS / Cell data with WiFi data by matching BSSIDs with an online database (within Google etc) to get rough location information.


How can I find the time taken while a function is being called? I tried using millis, but I wanted to know if there is any better way to find out the exact time from when a function is called and finally when it terminates.

There is micros() which returns the number of microseconds the board has been active. But it rolls over much more frequently (a bit over an hour vs the month and a half for millis())

unsigned long preFunction = micros();
foo();
unsigned long timeElapsed = micros() - preFunction;


Is the ShiftOut tutorial on the official Arduino website really wrong regarding the capacitor? I'm talking about this tutorial "Serial to Parallel Shifting-Out with a 74HC595" from the official Arduino website. It provides the following schematic:

I've read a couple of times now, that the placement of the capacitor is wrong:

  This is a well known shit tutorial which for some unknown reason they refuse to fix.
  That capacitor should be connected between the Vcc pin and ground, NOT the latch pin.

Source: forum.arduino cc/index.php?topic=408135.0

They recommend this placement:

Who's right? Please explain where to place the capacitor. Can the arduino even be damaged?

You can figure out the impedance of that capacitor for high frequency signal....

What they have there is really a low pass filter.

Terrible ideal to out that big of a capacitor there.


Arduino stopped working: avrdude: ser_open(): can't set com-state I'm playing with my first Arduino device (Arduino Leonardo). It worked fine but at some point it failed. I'm getting this error:

  avrdude: ser_open(): can't set com-state for "\.\COM6"

  An error occurred while uploading the sketch

The error came out of nowhere because I didn't change the port or cable or anything. Everything seems to be in order: the port, the driver, the IDE, the cable. And everything worked just an hour ago.

1) I've tried to change the port
2) I've reinstalled IDE
3) I've tried different cable

What else can I do?

And another thing: after manual reset of Arduino (with button) device disappears.

The thing to remember with the Leonardo and other ATMega32U4 based boards is that there is no actual serial connection.

What there is, is a USB connection which is controlled by the sketch (and independently by the bootloader) to provide a "CDC/ACM" connection over USB.  This emulates a serial connection, but it's not a real serial connection.

This actually has a huge number of benefits, because you can be other things besides a serial port, such as a keyboard or a mouse. However, it comes at a cost:  the serial port is at the mercy of the sketch that's running at the time.

If your sketch crashes for any reason then the serial port can no longer be used. That's bad. It can cripple your Arduino. Since it's the sketch that is providing the driving force for the CDC/ACM serial emulation, if that sketch dies, so does the control of the USB and thus the CDC/ACM.

So while the port may be created initially by the sketch, if it then subsequently crashes the port is still there, but unresponsive.  Or the port can vanish completely.

So how do you fix it?  Well, there's a couple of strategies:

Some people have had success by pressing the RESET button twice in quick succession. This depends on the version of the bootloader in use though, and it's not something I have ever tried.
Pressing RESET at just the right moment to get the bootloader to run just before avrdude runs and catch it at the right time to accept a new sketch, or
Using a hardware programmer (e.g., USBASP) or another Arduino to wipe the chip and reinstall the bootloader

My preferred method is 3, since it is certain to always work - however it requires either a hardware programmer or another Arduino. However you can pick up a USBASP on eBay / AliExpress / Amazon etc for next to nothing, and when you're working with AVR chips they're always good to have to get you out of tight spots like this.


My Digispark board won't show up in Ports tab in Arduino IDE (OSX) I bought a Digistump/Digispark board online and when i received it, I plugged it into my iMac to see if it works. I went to the apple in the top left corner and clicked "About this Mac". Then I clicked "System Report" and I went to the USB tab and it showed something connected as:

"Vendor-Specific Device:"

I was glad that it showed up but when I went to the Arduino IDE it didn't show up in the ports tab. I downloaded the AVR pack and the driver (i'm pretty sure the driver should work, if there is a specific driver that will work could someone send me to it) I am really frustrated and mad because it seems like this always happens. If someone could help me that would be greatly appreciated! Thank You.

Atmel 1624 tiny85

I don't think it is supposed to. The Digispark briefly connects in "bootloader" mode, which you spotted as "Vendor-Specific Device:".

Then after 5 seconds it runs the loaded sketch. If your sketch doesn't create a USB port (eg. a keyboard) then it will disappear from the USB list.

See:

http://digistump.com/wiki/digispark/tutorials/connecting

You don't select the port, the core files automatically find the Digispark and program it. You have to plug in the Digispark when instructed, to activate the bootloader.


Unable to get Arduino Ethernet Shield IP address connected to Raspberry My Arduino Uno with Ethernet Shield is connected to a Raspberry (rasp1) and the Ethernet Shield is connected to another Raspberry (rasp2) by Ethernet cable; rasp2 has a private IP address (192.168.10.0). I want to find out the Arduino IP address.

I used the example sketch  DHCPAddressPrinter but when running it the Serial Monitor remains empty (as Mac Address I used the address located underneath the shield).

Code Used:

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

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
    0x90, 0xA2, 0xDA, 0x11, 0x32, 0x49
};

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
    // Open serial communications and wait for port to open:
    Serial.begin(9600);
    // this check is only needed on the Leonardo:
    while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
    }

    // start the Ethernet connection:
    if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // no point in carrying on, so do nothing forevermore:
        for (;;)
        ;
    }
    // print your local IP address:
    Serial.print("My IP address: ");
    for (byte thisByte = 0; thisByte < 4; thisByte++) {
        // print the value of each byte of the IP address:
        Serial.print(Ethernet.localIP()[thisByte], DEC);
        Serial.print(".");
    }
    Serial.println();
}

void loop() {

192.168.10.0 is not a valid IP address (unless it's on a /32 subnet which makes no sense on ethernet).

You need to allocate a proper IP address within a proper subnet, such as 192.168.10.1/24 (i.e., IP 192.168.10.1 and netmask 255.255.255.0), and either manually provide a similar IP address to the Arduino (such as 192.168.10.2/24 [IP 192.168.10.2 netmask 255.255.255.0]), or install and configure a DHCP server on the Raspberry to hand out IP addresses within that subnet range (e.g., 192.168.10.100/24 to 192.168.10.200/24) for the Arduino to then be able to use DHCP mode.

Most of that is outside the scope of an Arduino SE site, though.


Cycling LED's for specific time period with millis() My goal in pseudo code is :

only LED-6 HIGH for 6 seconds, then only LED-7 HIGH for 2 seconds, then only LED-8 HIGH for 4 seconds, then restart

This is very easy with delay(), but I struggle with millis(). Here is my code. Only led 7 and 8 blinks.

unsigned long currentTime;
unsigned long previousTime1 = 0;
unsigned long previousTime2 = 0;
unsigned long previousTime3 = 0;
unsigned long interval1 = 6000;
unsigned long interval2 = 2000;
unsigned long interval3 = 4000;

void setup() {

  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);

}

void loop() {

  currentTime = millis();

  if (currentTime - previousTime1 >= interval1){
    previousTime1 = currentTime;
    digitalWrite(6, HIGH);
    digitalWrite(7, LOW);
    digitalWrite(8, LOW);
  }

  if (currentTime - previousTime2 >= interval2){
    previousTime2 = currentTime;
    digitalWrite(6, LOW);
    digitalWrite(7, HIGH);
    digitalWrite(8, LOW);
  }

   if (currentTime - previousTime3 >= interval3){
    previousTime3 = currentTime;
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    digitalWrite(8, HIGH);
  }
}

A way to make this work is to use only one previousTime variable, rather than three of them.

When the program as shown above starts out, millis() is in fact close to 0, so none of the three LEDs should light up in the first 2 seconds.  At the 2 second mark, LED 7 comes on.  previousTime2 gets set to current time, so the second if is not going to be satisfied for 2 more seconds.  At that point, LED 7 and 8 are in a race to see which one turns on second; whichever turns on first at the 4-second mark gets turned off within milliseconds, because when any LED turns on, the code turns off the other two LEDs.  Whenever the condition for LED 6 is met, so is the condition for at least one of 7 or 8; so 6 can't stay on more than 2 seconds at most, and even then is in a race with 7 and 8 to come in third.

With a single previousTime variable, code like the following might work.

current = (millis() - previousTime)/1000;
if (current < 6) {
  digitalWrite(6, HIGH); // turn on 6
} else {
  digitalWrite(6, LOW);  // turn off 6
}
if (current >= 6 && current < 8) {
  digitalWrite(7, HIGH); // turn on 7
} else {
  digitalWrite(7, LOW);  // turn off 7
}
if (current >= 8) {
  digitalWrite(8, HIGH); // turn on 8
} else {
  digitalWrite(8, LOW);  // turn off 8
}
if (current >= 12) {
  previousTime = millis();
}

Note, the following code has the same effect.

current = (millis() - previousTime)/1000;
digitalWrite(6, current < 6);                 // turn 6 on or off
digitalWrite(7, current >= 6 && current < 8); // turn 7 on or off
digitalWrite(8, current >= 8);                // turn 8 on or off
if (current >= 12) {
  previousTime = millis();
}


Disable SCK temporarily to save power for logging of environmental data, I am using a MicroSD card adapter (no brand name, eBay, China) and a 4GB Intenso SD card. I want to read data and write it to the SD card once every 10 minutes. Power consumption needs to be as low as possible.

Between the measurement points, I switch off the power supply to my sensor and SD card adapter using an NPN transistor (BC547B, 2N3904, 2SC945) and put my controller to sleep using jeelib. Everything works fine!

But I realized, that even during sleep, still 1mA of current is drawn. This disappears, when I remove the SCK connection between the Arduino and the SD controller. Doesn't sound like a lot, but for my purposes, it's a major concern (when SCK is removed, I'm around 6µA during sleep).

Is it possible to switch the SCK signal off during sleep to save that last bit of power?

In case it matters, I am using the SdFat library to write to SD. Initialization is done before each write. I figured, this would be necessary because of the poweroff of 10 minutes. Here's the function:

#include <SdFat.h>
const int chipSelect = 10;
String outfilename = "Bienen.log";

[...]

int writeToFile(String outfilename, String writestring) {

  SdFat SD;
  if (!SD.begin(chipSelect)) {
#ifdef DEBUG
    Serial.println("Card failed, or not present");
    error_signal();
#endif
  } else {
#ifdef DEBUG
    Serial.println("card initialized.");
#endif
  }

File outfile = SD.open(outfilename.c_str(), FILE_WRITE);
#ifdef DEBUG
  Serial.println(outfile);
#endif
  if (outfile) {
    outfile.println(writestring);
    outfile.close();
#ifdef DEBUG
    Serial.println("Wrote successfully.");
    ok_signal();
#endif
    return 0;
  } else {
#ifdef DEBUG
    Serial.println("Writing failed.");
    error_signal();
#endif
    return 1;
  }
}

ok_signal() and error_signal() are merely functions to flash an LED.

EDIT:
Thanks for your reply! I tried the code snippets

SPCR &= ~_BV(SPE)

and

SPCR |= _BV(SPE)

at the appropriate places, although I did not understand them. There was, however, no change in power consumption - SCK still seems to run.

I could not adapt the physical changes detailed in the suggested wordpress article, as the adapter there is quite different from my microSD adapter, and I know too little about hardware to adapt the author's suggestions. It looks and sounds quite promising though ...

Thanks for your time! Any help is greatly appreciated!

Re-visiting the issue, I have found a simple answer:

I set the SPI pins as outputs and inputs respectively:

const int chipSelect = 10;
const int MOSIPin = 11;
const int MISOPin = 12;
const int SCKPin = 13;

and

  pinMode(chipSelect, OUTPUT);
  pinMode(MOSIPin, OUTPUT);
  pinMode(MISOPin, INPUT);
  pinMode(SCKPin, OUTPUT);

Now, before I power down my machine, I do the following:

  SPI.end();
  digitalWrite(SCKPin, HIGH);
  digitalWrite(chipSelect, HIGH);
  digitalWrite(MOSIPin, HIGH);

Now, the drawn current drops from 1mA to roughly 0,02mA, which is satisfactoy for me!

Thanks for reading!


ESP8266 SoftwareSerial not receiving any character I want to use a ESP8266 (ESP12) to receive data from a counter at 9600 baud via SotwareSerial. But my program does not receive any data. I broke it down to the code i attach here. I tried it using different libraries (Arduino SoftwareSerial and also espsoftwareserial) i found. I connected and tested RX and TX in different combinations of the available pins 4/5/12/13/14. But no combination is receiving data at all. I only can send data - checked by oscilloscope. Running my test program attached i connected the RX and TX pin together so i should loop back the data from tx.

I hopefully find somebody in the community who can give me a helpful hint. Thank you in advance!

#include <SoftwareSerial.h>
SoftwareSerial mySerial1(14, 12, false, 256);  // RX, TX

void setup() {
mySerial1.begin(9600);   //  Kommunikation mit Zähler
mySerial1.setTimeout(5000);
mySerial1.listen();
//delay(100);
//mySerial1.listen();

Serial.begin(9600);
delay(1000);
Serial.print(__DATE__);Serial.print(" ");Serial.println(__TIME__);

char ch;
while(1){
  wdt_reset();
  Serial.println("\nSoftware serial test started");
  Serial.print("Data sent: ");
  for (byte i = 32; i < 128; i++) { mySerial1.write(i);
  Serial.print(char(i)); }
  Serial.println();
  mySerial1.println();
  ESP.wdtFeed();
  delay(100);
  Serial.print("Data recv: ");
  if(mySerial1.available()) {
    while(mySerial1.available()){
      ch = mySerial1.read();
      Serial.print(ch);
    }
    Serial.println("_");
  }
  delay(400);
}
}

void loop() {}

If the ESP8266's software serial is anything like the Arduino's software serial, it cannot receive data while it's transmitting. It's strictly half-duplex.

To test your system you will need to test the transmission and reception completely separately, and that means having some external device sending data for you to attempt to receive.


micro arduino and w5100 I would like to ask if it is possible and how to connect the following module
http://www.ebay.com/itm/TOP-Mini-W5100-LAN-Ethernet-Shield-Network-Module-board-for-Arduino-Best-NEW-/251981053942?pt=LH_DefaultDomain_0&hash=item3aab3dbff6

to the arduino micro

I found some pin layouts but only for Leonardo or Ethernet shield, Uno etc.

Also I've choosen this model because it can be programmed directly in arduino using Sockets API

While it would have been nice to see your research rather then having to spend some time finding this information myself, I did find this http://www.instructables.com/id/Add-Ethernet-to-any-Arduino-project-for-less-than-/ from what I can see this should be compatible to any arduino as long as it has 3 volt pin and 4 i/o pins. While the arduino micro doesn't have a 3v3 pin, as far as I know, that shouldn't be an issue as long as you can drop the voltage from the 5 volt pin, this module should work for you.


HM-10 discovery issue i am not able to detect any android device on my bluetooth HM-10 module which is connected to arduino. i am able to see my bluetooth module on my android phone. but i want to see android phones on arduino serial monitor for that i used AT+DISC? command. it shows AT+DISCS and than AT+DISCE with a 2 second interval. help me to solve the issue
thanks in advance

The HM-10 is a BLE-only device.

Android phones do not normally transmit BLE advertisements, so there is normally nothing about an Android phone for it to discover.

The exception would be if you have software on a late Android version with the capability, which you have set up to intentionally transmit BLE advertisements, or else if software you put on your Android phone is actively responding to advertisements you had the HM-10 transmit.

Essentially, you are expecting something that his not normal behavior, but will only be achieved by adding your software on both devices.