Button with switch timer and reset time function + LED feedback. What am I doing wrong? Beginner here.

I´ve been trying to implement a button function timer working with millis() instead of delay as I want the button to be responsive while the timer is running.

So far I´ve managed to start the counter on the button´s state change and let it time out. Unfortunately all kind of strange behavior is coming out of my sketch and I am yet to understand why.

Help is appreciated.

This is the desired behaviour of the timer:

On startup the Arduino is ready to recieve a button push.
The relay is off (HIGH).
Once the button is pushed:
• The relay state is changed to LOW in order to turn it on
• A green LED switches on.
• A millis() based timer is switched on.
If the user presses the button while the switch is on, the timer is reset to 0 and continues counting.
If the on-time is going to end, a red LED starts blinking. Say in the last minute.
As soon as the timer reaches the specified on-time:
• The green LED switches off
• The relay switches off
• The system returns to step 1. and is awaiting a push.

In my code example the red blinking Led is not implemented yet.
The following code switches the switch and the green LED on but does not switch them off anymore.

//CONSTANTS

#define BUTTON_PIN        2  // Button
int in1 = 7;
int greenLED = 4;
int redLED = 9;

//VARIABLES

int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

//MILLIS
unsigned long previousMillis = 0;
const long interval = 10000;

void setup()
{
  pinMode(BUTTON_PIN, INPUT);
  digitalWrite(BUTTON_PIN, HIGH); // pull-up
  Serial.begin(9600);

  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);

  //SWITCH HANDLERS
  pinMode(in1, OUTPUT);
  digitalWrite(in1, HIGH);

}

void loop(){

    // read the pushbutton input pin:
    buttonState = digitalRead(BUTTON_PIN);
    unsigned long currentMillis = millis();

    // compare the buttonState to its previous state
    if (buttonState != lastButtonState) {

        buttonState = digitalRead(BUTTON_PIN);

        if (currentMillis - previousMillis < interval){
        //SWITCH ON, LED ON
          digitalWrite(in1, LOW);
          digitalWrite(greenLED, HIGH);
        }

        if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            digitalWrite(in1, HIGH);
            digitalWrite(greenLED, LOW);
        }

        // Delay a little bit to avoid bouncing
        delay(50);

        // Reset buttonState:
        lastButtonState = buttonState;
   }
}

Written and tested. I also included the red blinking led.

//CONSTANTS

const int BUTTON_PIN = 2; // Button
const int in1 = 7;
const int greenLED = 4;
const int redLED = 9;

//VARIABLES

int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button
bool relayOn = false;

//MILLIS
unsigned long previousMillis = 0;
const unsigned long interval = 10000;
const unsigned long redLedInterval = 2000;

void setup()
{
  pinMode(BUTTON_PIN, INPUT);
  digitalWrite(BUTTON_PIN, HIGH); // pull-up
  Serial.begin(9600);

  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);

  //SWITCH HANDLERS
  pinMode(in1, OUTPUT);
  digitalWrite(in1, HIGH);

}

void loop(){

    // read the pushbutton input pin:
    buttonState = digitalRead(BUTTON_PIN);
    unsigned long currentMillis = millis();

    // if button is pressed, turn relay on (if it wasn't already on), and reset the timer
    if( buttonState==LOW ) // no need to check for previous state, in this specific case
    {
        previousMillis = currentMillis;
        digitalWrite(in1, LOW);
        digitalWrite(greenLED, HIGH);
        digitalWrite(redLED, LOW);
        relayOn = true;
    }

    // if relay is currently on...
    if( relayOn )
    {
        // turn red led on, if close to turning off the relay
        if (currentMillis - previousMillis >= interval-redLedInterval )
            digitalWrite(redLED, (millis()/300)%2);//blink red led; 300ms on; 300ms off

        // if enough time has elapsed, turn of the relay
        if (currentMillis - previousMillis >= interval)
        {
            // .. turn of relay
            digitalWrite(in1, HIGH);
            digitalWrite(greenLED, LOW);
            digitalWrite(redLED, LOW);
            relayOn = false;
        }
    }
}

Added advantage here is that the timer will never run out if the button is keep being pressed down.


Using analog in to read a push button I'm working on a project in which I use a lot of the pins on the Arduino;  I have run out of most of the pins and and I need to read the value of a push button.

Is it possible to read the value of the switch in the analog in pins on the board??

If so how can I implement this?

Is it possible to read the value of the switch in the analog in pins on the board??

Yes. Analog input pins are also digital IO pins. You can use them exactly the same way as all the other pins on the board.


Arduino Due not properly detecting SD card I have an SD breakout for my Due that isn't properly detecting the SD card. On one card, it cannot detect at all, and the other it says that the SD isn't formatted with FAT, even though it is. Here is my wiring:

simulate this circuit – Schematic created using CircuitLab

So, I broke out my oscilloscope and started probing lines. One in specific I got worried about, is the SCK line and it's bouncing, specifically from the inductance of the jumpers. This is the SCK line from my scope:

My reaction was to put some buffer caps on there, and so I put 2x 300pf capacitors in parallel for a total of 600pf. This is the waveform as measured after I put in the debouncing caps:

This is much more tolerable, and I can accept this level of bouncing for the SCK line, as I doubt that there will be much misfiring. I upload the SD card test sketch that's on the website, here is the output:

Initializing SD card...Wiring is correct and a card is present.

Card type: SD2
Could not find FAT16/FAT32 partition.
Make sure you've formatted the card

What does The Arduino Due have that makes it hard to detect the card?

Remove the caps please. Perhaps the scope itself creates the overshoot.

The Due is not special. It should work.

Can you tell what kind of SD memory cards and which SD module you use ?

Try the SD Formatter, see the post at the Arduino.cc forum: "Don't Format SD cards with OS utilities!".
Some SD memory cards are not compatible. Perhaps you have more luck with an older 1GB or 2Gb SD memory card.


How to get the ID of an Arduino? I use Arduino Pro Mini. As I know, every MCU has a number. Different MCU has different number.  How to get it ?

Arduino Pro mini is based on Atmega328 which does not have a unique ID. It has only device signature which you can read if you turn on Show verbose output during upload in Arduino IDE's File > Preferences.


POST to server using ESP8266 module- Arduino Uno- AT+ commands I'm trying to send a set of data in Json format to a server I have set up which has a specific URL and an access token. The server requires a POST command. So my final URL is: http://myurl.com/myaccesstoken

The idea is that the Arduino UNO acquires some data from a sensor it then uses the ESP8266 to connect to wifi and send the acquired data to my server.

I do not understand why my server does not receive data

Thank you a lot in advance for your help.

I have used the following code:

#include "Arduino.h"
#include "ESP8266.h"
#include "SoftwareSerial.h"
#include "ArduinoJson.h"

#define ssid "mySSID"
#define pw "myPW"
#define IP "xxx.xxx.xxx.xxx"
#define URL "http://myurl.com/myaccesstoken"

int incomingByte;

void setup() {//I connect to wifi
  Serial.begin(115200);
  Serial.println("AT");
  delay(5000);
  analogReference(INTERNAL);
  if(Serial.find("OK")){
    Serial.println("AT+CWMODE=3");
    delay(1000);
    String WF=String("AT+CWJAP=\"")+ssid+"\",\""+pw+"\"";
    Serial.println(WF);
    delay(5000);}
}

void loop() {
  //JSON data creation
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["flow"] = 2.54;
root["measured"] = "2017-08-14T06:16:03.418Z";
root.printTo(Serial);
delay(5000);
 // I start communication with server
 Serial.println(String("AT+CIPSTART=\"TCP\",\"") + IP + "\",80");
 delay(5000);
 Serial.println("AT+CPSTATUS");
 // I use HTTP protocol to POST the data
    Serial.println("AT+HTTPINIT");
    delay(2000);
    Serial.println("AT+HTTPPARA=\"CID\",\"1");
    delay(2000);
    Serial.println("AT+HTTPPARA=\"URL\",\"http://myurl.com/myaccesstoken\"");
    delay(2000);
    Serial.println(String("AT+HTTPPARA=\"CONTENT\",\"application/json"));
    delay(2000);
    Serial.println("AT+HTTPDATA=\" + 81 + \",1000"); //81 is the computed length of my JSON
    delay(2000);
    Serial.println("AT+HTTPACTION=1");
    delay(2000);
    Serial.println("AT+HTTPREAD");
    delay(2000);
    if(Serial.available() > 0)
        {
                // read the incoming byte:
                incomingByte = Serial.read();
                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte);
    }
    Serial.println();
    Serial.println("AT+HTTPTERM");

    delay(5000);
  }

Your code doesn't work because you start by sending ESP-specific AT commands to open a socket, then you suddenly switch to SIM800-specific AT commands, and the ESP goes "WTF dude?!"

I suggest you read some tutorials on accessing web sites with the ESP8266 not with the SIM800.


Is parity check hardware only or can I read it? ( Arduino Mega ) Maybe a simple question, but I can't seem to find it.

Parity check is simple error detection.

But is in done in hardware on the arduino and is the data discarded before i can read it from software?

The reason I ask this quote from Thomas

  1  Command bit, set on the first character of each datagram. Reflected in the parity bit of most UARTs. Not compatible with NMEA0183 but well suited for the multiprocessor communications mode of 8051-family microcontrollers (bit SM2 in SCON set).

From http://www.thomasknauf.de/rap/seatalk1.htm#Dat which might have confused me. So I guess this is not an option ... after the feedback from users.

So i need to read the 9 bit and since the hardware support it. The Arduino team won't implement it, since it has a bigger overhead and it's really not used anymore ... I agree ... but the SeaTalk bus uses it ... so I'm stuck here.

But after more seaching I found this GitHub repo: https://github.com/rob42/FreeboardPLC_v1_2 which have made changes to the HardwareSerial.h and HardwareSerial.cpp but only for version 1.5.7

Think I will go for this version unless someone have done the mods to 1.6.x ... have searched the web. Later I will try to see if I can get it to work with 1.6.x ... but since this is all new. I'm taking small steps.

This came up a while back on the Arduino Forum - talking about Asynchronous SeaTalk.

I made a modified version of HardwareSerial which can be downloaded from http://gammon.com.au/Arduino/HardwareSerial9bit.zip

Changes are:

The internal buffers have been changed from 8-bit characters to 16-bit characters (to hold the 9th bit). Thus the buffers double in size.
There is a new argument to the Serial.begin() function, which is a boolean, whether or not you want 9-bit mode. It defaults to false.
There is a new function Serial.write9bit (). This takes an unsigned int argument, letting you supply a character with the 9th bit set. I didn't want to change the existing write function because it is used in the Print class.
The read function, which already returns an int, now will return the 9th bit where required.

Example code:

void setup ()
{
 Serial.begin (115200);  // debugging prints
 Serial1.begin (115200, true);  // 9 bit mode
 Serial2.begin (115200, true);  // 9 bit mode
 Serial.println ("--- starting ---");
}  // end of setup

int i;

void loop ()
{

 Serial1.write9bit (i++);  // send another byte

 // display incoming on Serial2
 if (Serial2.available ())
   Serial.println ((int) Serial2.read (), HEX);

 // check if we have sent all possible characters
 if (i >= 0x200)
   {
   delay (100);
   while (Serial2.available ())
     Serial.println ((int) Serial2.read (), HEX);
   delay (5000);
   i = 0;
   }  // end of sent 512 bytes
}  // end of loop

As Ignacio Vazquez-Abrams said, the hardware supports this 9-bit mode natively, it just takes a bit of fiddling around to make it work.

Because of the way that hardware serial is integrated into the IDE it is, unfortunately, necessary to find your existing files:

HardwareSerial.cpp
HardwareSerial.h

... and replace them with the ones in the download.

Note that this is for version 1.0.1 of the IDE. No guarantees are given that this will work with other versions. This was written a while back, I'm not sure what changes have been made to HardwareSerial in the meantime.

The actual changes are here: http://gammon.com.au/Arduino/hardwareSerial_diffs.txt

You could use those to guide your implementation on more recent versions, if the file download does not work "as is".


DFRobot GPS init error [Arduino Uno, SIM808] i have problem with initialization DFRobot SIM808 actually when i try to recieve gps data by SoftwareSerial only it does works (i mean examples based on sending and reading command to and from serial's), and recieve data but very long string of data and i need only Latitude and Longitude and i think using DFRobot will be the easiest way to extract the data i need. So the simple test program like this one is not working:

    /*
### Get GPS data
1. This example is used to test SIM808 GPS/GPRS/GSM Shield's reading GPS data.
2. Open the SIM808_GetGPS example or copy these code to your project
3. Download and dial the function switch to Arduino
4. open serial helper
4. Place it outside, waiting for a few minutes and then it will send GPS data to serial

create on 2016/09/23, version: 1.0
by jason

*/
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>

#define PIN_TX    7
#define PIN_RX    8
SoftwareSerial mySerial(PIN_TX,PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

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

  //******** Initialize sim808 module *************
  while(!sim808.init()) {
      delay(1000);
      Serial.print("Sim808 init error\r\n");
  }

  //************* Turn on the GPS power************
  if( sim808.attachGPS())
      Serial.println("Open the GPS power success");
  else
      Serial.println("Open the GPS power failure");

}

void loop() {
   //************** Get GPS data *******************
   if (sim808.getGPS()) {
    Serial.print(sim808.GPSdata.year);
    Serial.print("/");
    Serial.print(sim808.GPSdata.month);
    Serial.print("/");
    Serial.print(sim808.GPSdata.day);
    Serial.print(" ");
    Serial.print(sim808.GPSdata.hour);
    Serial.print(":");
    Serial.print(sim808.GPSdata.minute);
    Serial.print(":");
    Serial.print(sim808.GPSdata.second);
    Serial.print(":");
    Serial.println(sim808.GPSdata.centisecond);
    Serial.print("latitude :");
    Serial.println(sim808.GPSdata.lat);
    Serial.print("longitude :");
    Serial.println(sim808.GPSdata.lon);
    Serial.print("speed_kph :");
    Serial.println(sim808.GPSdata.speed_kph);
    Serial.print("heading :");
    Serial.println(sim808.GPSdata.heading);
    Serial.println();

    //************* Turn off the GPS power ************
    sim808.detachGPS();
  }

}

We had the same error in the code. But we managed to solve it! You have to insert the SIM CARD to work. We do not know why, but it works!


"Active LOW" relay board Pin configuration I bought a 5 V Relay Board: LINK (Aliexpress) and just realised it's "Active LOW".
I want to control a water pump via a Arduino Micro.

I tested it and as far as i understand the workings of this relay, putting the pin to LOW activates the little LED on the Relay Board and switches to the NC position where I connected the water pumps ground wire.

I don't feel very comfortable with that because normally those relays are activated by setting the pin to HIGH.
I tried to connect the ground wire of the pump to the normally open position but than, if I disconnect the Arduino to simulate a malfunction the pump keeps running.... this doesn't happen with the first configuration.

So my Question: Is it a problem to use the Relay Board in the way described above (Pin to LOW switches Coil to NC Postion).
Is there a way I'm not seeing to get the Board to switch the Coil if a pin is set to high.

That relay module is driven by optocouplers. You are just driving and LED, and that is connected though a resistor to VCC.

In the past it was common to use active low for driving things since an N channel MOSFET could typically sink more current than a P channel one could source. Also in the days before CMOS there was really only low-side (sinking) switching, so active low was the norm.

These days it's not necessary, but it's still common because that is how it's always been.

So yes, active low is both common and accepted.


Space needed for local String variable I tried to run this code on my Arduino Uno clone (which has no function so far and is a shortend version of my programm):

String rules [16][5] ={
   {"B0 B5", "", "", "cs S0", "", },
   [...]
};

void setup() {
  Serial.begin(9600);
  String foo = "bar";
  Serial.println(foo);
}

void loop() {
}

I left the rules array out, but it is quite big. It isn't used yet, but it contains rules how to react on certain situations (which should be used later).

As the Arduino IDE gives the following after complilig:

Sketch uses 4316 bytes (13%) of program storage space. Maximum is 32256 bytes.
Global variables use 1174 bytes (57%) of dynamic memory, leaving 874 bytes for local variables. Maximum is 2048 bytes.

When I run this sketch there is nothing on the serial monitor. If it works, there should appear bar, but it does not. The Arduino sends only a linebreak over the serial, but no text.

When I remove some characters from that array so that there are about 900 bytes the script works and prints bar to the serial monitor.

So, aren't 874 bytes not enough to store a three-character string? Why does it need 900 bytes to store such a short string?

You are requesting 80 String objects.

Each String object allocates memory to store its data. When you provide a string constant that string constant data's length is used for the allocated data size (including the NULL character at the end), and the string constant data copied in.

On top of that you have a bunch of other data that is needed for the String class to do its work. The total size of a String object is 6 bytes.

So the memory you need for your array of Strings can be calculated as:

Let C be the total number of characters in all the string constants
Let N be the number of String objects in the array
Let T be the total number of bytes.

T = N * 6 + C + N

With no string constant data that would be:

T = 80 * 6 + 80

That's 560 bytes already, before you even start thinking about putting in the string constant data.

Also you may like to add to that the fact that the compiler may (though I am not certain on this) be also copying the string constants into RAM first because they aren't forced into PROGMEM with the F() macro.

So since you only have 2KiB of RAM to begin with, and a quarter of that is instantly gobbled up with your array, you can see how things might not be too happy.

Oh, and the String's internal storage is allocated at run time, not compile time, so the compiler can't know that it'll overflow - only when you run the program will it overflow and things go horribly wrong.

So you need to ask yourself "Why do I even want an array of String objects?" and the answer is most certainly: "Under no circumstances do you ever want an array of String objects". In fact I am a strong advocate of never using String objects ever, for any reason whatsoever.

If your data is constant there is absolutely no reason to store it as String objects. It's constant. It should remain constant. Copying it into a String object means it's no longer constant and wastes many many resources.


Does Arduino.cc silkscreen the pin headers? What explains the differences here? I have two Arduino's. One from .org, and one from .cc. The arduino.org one has really nice silk screening on the header pins. The arduino.cc one does not. In addition there are some visible component differences. One has a 504S (not sure what this chip is), one has a 504L. The button on the .org one is a bit more tactile. The headers on the top (not the ICSP) headers are missing on the .org one. And, the four points that look like they're for soldering or testing are absent. I can try to get a high-res picture of the two up.

I bought the .org one in a beginner kit online from Amazon (from the official seller). And, the .cc I bought from their website directly.

The .org one seems like it's made from higher-end components, and actually having the headers at the top makes it seem more polished. Is there any through guide to what these differences are or a changelog from one hardware revision to another?

No, there is nothing that documents the differences as in a changelog, purely because this is not an iterative change.

The two boards are designed and manufactured by two different (competing) companies in two different countries (USA and Italy) using different component suppliers.

Just because they both say Arduino UNO doesn't make them both the same board - not these days anyway, since the founders of Arduino got really childish and started throwing their faeces at each other like monkeys in the zoo.


How to confirm a pin is fried How do you confirm a pin has been damaged and is unable to work as a digital input?

I tried detecting a pushbutton (connecting ground to pin 11 with a pullup resistor enabled) on a fresh Arduino Uno and digitalRead() always registers 0, regardless of the pushbutton state.

To confirm it wasn't my pushbutton's wiring, I tested it on some other pins, and they register the button press perfectly. I then tested pin 11 as an output, and it was able to blink and LED just fine.

The Arduino's pretty new, and I don't remember doing anything with it that would have damaged anything, much less pin 11, but is it fair to say that pin has somehow been damaged? As far as I can tell, everything else on the Arduino works perfectly.

Yes, it sounds like that pin is fried.

You seem to have done all the things I would recommend:

Try your circuit on a different pin (works fine)
Try your circuit on the same (faulty) pin on a different microcontroller (works fine)

If you get different results between two chips that should be the same with the same code running on them then one of them is most likely faulty in some way, or has some other setting in it (fuse setting) that could be affecting it.  I am not aware of any settings like that on the '328P, certainly none that you would change without knowing you had changed them.


Error on UNOr3--> avrdude: ser_open(): can't open device "/dev/ttyUSB0": No such file or directory ioctl("TIOCMGET"): Inappropriate ioctl for device When I try to upload my program on the Arduino Uno Chinese clone, It says

 -> avrdude: ser_open(): can't open device "/dev/ttyUSB0": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

My Arduino Programmer: ArduinoISP
My Arduino Software version: 1.6.8
My OS: Linux Mint

Can you help me fix this error?

This could be any number of different problems.  Here are several common causes:

You have multiple USB serial port devices connected to your computer. Try using the command ls -l /dev/ttyUSB* to check if your computer thinks there are more than one terminal USB device.  Disconnect all of them, then only connect the Arduino Uno.  Then repeat the check.
You do not have permissions.  This is tricky to check as Linux offers a flexible but complicated root, group and user permission paradigm.  You should NOT make a habit of this, but, for a quick check, you can try running the Arduino application as root and check if you can upload a sketch to the Arduino Uno.
You have a counterfeit FTDI chip on your Arduino Uno that has been rendered useless by certain versions of the Windows FTDI Driver.  The USB IDs can get reset to useless values.  I believe the current FTDI Windows Driver no longer does this.
You did not install the Linux FTDI driver.  A driver is a program to abstract the hardware from the application.  In this way, different hardware can be treated the same by the application, simplifying the application.  However, the wrong driver/hardware combination may not work as expected.


Speed data logging using arduino and GPS module I am using a Quectel L80-R GPS Module coupled with an Arduino UNO to read and log my car's coordinates and speed. I am currently using TinyGPS++ library which works okay. It does spell out coordinates and speed but with some inaccuracies and delays. After some literature review I realized that NeoGPS library might be a better option. I found a thread over stackexchange where a code block is provided written by slash-dev who most possibly is the writer of NeoGPS library. However, when I am trying to compile the code, I get the following error
'class gps_fix' has no member named 'lat' .I can not get rid of the issue even tough I've tried a whole bunch of workarounds.

According to the NeoGPS documentation for the gps_fix class, it looks like .lat and .lon are no longer part of the gps_fix class.
It looks like instead you will have to use .latitudeL and .longitudeL for high precision (Long Integer scaled by 10,000,000) GPS coordinates.
The solution would be to replace fix.lat in your code with fix.latitudeL and fix.lon with fix.longitudeL.


Upload original firmware to HID Arduino I recently was playing around with Arduino and using dfu-programmer reflashed ATMega16u2 to make the computer think it was a keyboard device.

Well, I wish to put the original Arduino firmware back on, but now dfu-programmer says the device is not present.

The Arduino is listed under /dev/hidraw5 on Ubuntu. Typing lsusb gives the following output for Arduino keyboard:

Bus 004 Device 008: ID 03eb:2042 Atmel Corp. LUFA Keyboard Demo Application

I tried erasing with the command:

sudo dfu-programmer atmega16u2:4,8 erase

and got

dfu-programmer: no device present.

Is there a way to target /dev/hidraw5 using dfu-programmer? Many thanks.

Very sorry!  But I actually figured this out on my own.  I needed to reset by briefly bridging the reset pin with ground near the USB connector.  Then typed

sudo dfu-programmer atmega16u2 erase

and I'm happy again.


Cannot convert 'int (*)[size]' to 'int**' Analyzing this and this answers under Arduino, which should be the proper way to pass a 2D array into a function?

The function should be applicable to different sizes of 2D arrays.

// NOT COMPILING EXAMPLE
void f(int** x,const int m, const int n){
// access x as x[0][0], x[0][1], etc...
}

void main{}{
    int x1[16][128];
    f(x1,16,128);
    int x2[64][16];
    f(x2,64,16);
}

According the prototype of f and the usage pattern for its x
argument, the function expects this argument to be a pointer to the
first element of an array of pointers to the first elements of arrays of
int. However, the matrix in main() is defined as an array of arrays
of int. If you try to pass this to a function, the matrix will decay
into a pointer to an array of int. That's not what you want.

If you want both dimensions of the matrix to be variable, the only
simple solution I see is to build an extra array of pointers (pointing
to the matrix rows) and pass that array to the function

int main() {
    int x[16][128];

    // Build an array of pointers to rows.
    int *px[16];
    for (int i = 0; i < 16; i++)
        px[i] = x[i];

    f(px, 16, 128);
}

For more information on this, see the section Arrays and Pointers in
the C FAQ, and more specifically the questions 6.16 (How can I
dynamically allocate a multidimensional array?) and 6.19 (How do I write
functions which accept two-dimensional arrays when the width is not
known at compile time?).


HC-06 data receiving I've written a script in Python which sends data through the PC's Bluetooth to HC-06 on Arduino.

state is an integer from 0 to 1000 (it is controlled through the potentiometer).

...
gaugeSocket.send(str(state))
...

I can't get the right character-to-integer conversion on Arduino (from HC-06 serial).

Arduino code:

SoftwareSerial mySerial(10, 11); // RX, TX
char buf[2];
int i=0;
int data;
int ledPin = 9;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(57600);
  mySerial.begin(9600);
}

void loop() {
  if (mySerial.available()) {
    for(;i<2;){
      buf = mySerial.read();
      i++;
    }
    i = 0;
    Serial.print(buf);
    data = atoi(buf);
  }
    analogWrite(ledPin, data/10); //To see how code behaves on LED
}

Serial print gives me this (if I turn potentiometer from 0 to 1000):

  0ÿ(0ÿ(0ÿ(0ÿ(0ÿ(0ÿ(0ÿ(60(1ÿ(00(16(0ÿ(23(0ÿ(30(0ÿ(3ÿ(60(43(0ÿ(49(0ÿ(53(0ÿ(5ÿ(90(69(0ÿ(88(0ÿ(10(00(10(00(10(

What am I missing? Is it because I'm sending it as a string? Or is my buffer not the correct size?

Here is your main problem:

if (mySerial.available()) {
    for(;i < 2;){
        buf = mySerial.read();
        i++;
    }
....

There you are saying "If there is at least one character available in the buffer then read lots of characters from the buffer".

You can't read characters that aren't there yet.

So your stream of data is interspersed with the integer -1 which means "I don't have any data to read!"

I explain it all here: http://hacking.majenko.co.uk/reading-serial-on-the-arduino

By the way - character -1 looks like this: ÿ

You are sending your data as text.  That means, to send the value 348 you are first sending the byte representation of the ASCII character "3", which is the decimal byte value 51.  Then you send the byte representation of the ASCII character "4", which is the decimal value 52, and finally you send the byte representation of the ASCII character "8", which is the decimal value 56.

You look to see if there is one byte available (if(mySerial.available())) and then read that byte into "buf" and increment "i" (by the way, "i" is never reset to 0 - your whole loop strategy is completely wrong, but that's a completely different issue).  You then read a second character and assign that to buf instead.

So if you have the character "3" in the serial buffer you then place that in "buf".  You then read whatever is next in the buffer, which 9 times out of 10 will be nothing, so read() returns -1.  So you just assign that to "buf" instead, replacing the "3" that was in there before.

But "buf" is a character array, and you are assigning a character to the whole array, which makes absolutely no sense (does the code even compile as you have shown it?).

Basically your whole reading routine is completely wrong and can never work no matter how much tweaking and advising we do.

The link I provided above describes not only how you should do the reading on the Arduino, but also how you should do the sending from the other end.  It is vitally important that you send something that says "This is the end of the number I am sending" so that the Arduino knows where one number ends and the next starts.  Normally that is done, when sending a textual representation of the number like this, by adding a line feed and/or carriage return at the end of your number.  So instead of sending "348" you send "248\n".

The Arduino then checks to see if there is one character available, and then it adds just that one character to the end of the buffer.  If, and only  if, that character is the delimiting character then you can take the buffer and translate it into an actual number and reset your buffer to be empty ready to receive the next number.

The link above has good example code showing you exactly how to do that.


Why PJ0 and PJ1 are not reporting as PCINT pins When the sketch shown at end-of-question is compiled and uploaded to an Arduino board, it is supposed to Serial-print a list of available digital pins, showing for each pin whether it supports PWM or PCINT.  (For the latter items, it should indicate whether it has timer-supported PWM, and whether it can cause a hardware-supported pin-change-interrupt.)  For example, for an ATmega-2560 board, the program's output includes lines like

  Pin# Port Mask  PWM  PCINT
  11   PB5  0x20  PWM  PCINT5  PCINT0_vect
  46   PL3  0x08  PWM
  52   PB1  0x02       PCINT1  PCINT0_vect

Using arduino 1.6.3 on my Ubuntu 14.04 system with an ATmega-2560 board, the program's output for pins 14 and 15 is:

  14   PJ1  0x02
  15   PJ0  0x01

As I understand it, those pins should be shown⁽¹⁾ as supporting PCINT9 and PCINT10, with vector PCINT1_vect, but the program doesn't report them as such.  What is this problem due to?

⁽¹⁾See, for example, table 13.3.9, Alternate Functions of Port J, in doc2549.pdf, the spec sheet for ATmega640/1280/1281/2560/2561.  Also see Why is my interrupt code not working?.

Sketch pinsList.ino:

/*  pinsList -- JW, 4 October 2015 --
 *
 *  Displays a list of Arduino pin numbers for current kind of Arduino
 *  board, along with port codes, pin-change-interrupt numbers, and
 *  pin-change-interrupt vector numbers.
 *
 *  Here are two examples of output lines for pin 11, the first for an
 *  Uno, the second for a Mega:
 *
 *        11   PB3   0x04   PWM   PCINT3  PCINT0_vect
 *        11   PB5   0x20   PWM   PCINT5  PCINT0_vect
 */
//-----------------------------------------------------------
// Given a value with 1 bit set, return bit #.  Else return 9.
byte getBitfromBV (byte m) {
  byte b=0, v=1;
  while (v) {
    if (m==v)
      return b;
    ++b; v <<= 1;
  }
  return 9;
}
//-----------------------------------------------------------
void processPinNumber(byte pin) {
  char buffi[128];      // We create text-to-write in buffi
  byte nbuff=0;         // #chars used in buffi
  byte nPCICR;          // 0, 1, or 2 for mask-register #
  byte bitInByte;       // 0 to 7 for bit in I/O mask
  byte pinPort;         // pin's port #, in range 1 to 12
  byte PCInum;          // PCINT# if pin is a PCI pin
  char *portLet = "?ABCDEFGHIJKL";

  if (pin >= NUM_DIGITAL_PINS) return;

  pinPort = digitalPinToPort(pin); // Get port #, in range 1 to 12
  bitInByte = getBitfromBV(digitalPinToBitMask(pin));

  nbuff = snprintf(buffi, sizeof(buffi), "  %2d   P%c%d  0x%02x",
           pin, portLet[pinPort], bitInByte, 1<<bitInByte);

  // Indicate if it's a PWM pin
  if (digitalPinHasPWM(pin)) {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "  PWM");
  } else {
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "     ");
  }

  // If it's a PCINT pin, show its PCINT number and 0, 1, 2 for its vector #
  if (digitalPinToPCICR(pin)) {      // Is it a PCint pin?
    nPCICR = digitalPinToPCICRbit(pin); // 0, 1, 2 for pin's PCICR bit#
    PCInum = nPCICR*8 + bitInByte;
    nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff,
             "  PCINT%d  PCINT%d_vect",  PCInum,  nPCICR);
  }
  Serial.println(buffi);
}
void setup() {
  delay(50);
  Serial.begin(115200);
  delay(50);
  while (!Serial) ;             // wait for serial stream to connect
  Serial.println("\nPin#  Port  Mask  PWM   PCINT");
  for (byte p=0; p<NUM_DIGITAL_PINS; ++p)
    processPinNumber(p);
  Serial.end();
}

void loop() {
}

Majenko was very close but seems to have missed the explanatory comment from the source code:

// (I've deliberately left out pin mapping to the Hardware USARTs - seems senseless to me)
// Pins: 10, 11, 12, 13,  50, 51, 52, 53,  62, 63, 64, 65, 66, 67, 68, 69

#define digitalPinToPCICR(p)    ( (((p) >= 10) && ((p) <= 13)) || \
                                  (((p) >= 50) && ((p) <= 53)) || \
                                  (((p) >= 62) && ((p) <= 69)) ? (&PCICR) : ((uint8_t *)0) )

Which seems like it may apply to the fact that the USART3 pins PJ1 (14) and PJ0 (15) are missing.

As for why providing mappings to the hardware USART pins "seems senseless" a little playing with git blame will show that these lines were added to this file in commit f179794  in response to issue 490:

  The SoftwareSerial library defines macros that map Arduino pin numbers to the pin changes interrupts on the pins.  We should pull this up into the board-specific pin definition header file so that the SoftwareSerial library can work on any AVR for which those macros (and the pin-change interrupts) are defined.

Which is to say that David Mellis didn't write those lines for generic interrupt use as part of pins_arduino.h, but rather moved code originally written as part of the software serial library to this file to make things more portable (and, though perhaps incidentally, generally usable for other purposes).  It's not exactly clear who the original author speaking as "I" in the comment is - the Mega-specific code in question appears to come most immediately from Mikal Hart's extension of Ladyada's Uno-only interrupt soft serial code (which did not have it) but there's also a comment in that seemingly crediting Paul Stoffregen (Teensy boards) for at least some aspect of the macro...

It does kind of make sense that someone writing a software serial library could consider using it on hardware serial pins pointless.  But counterarguments could also be made - for one example, the 16u2 core either uses or has experimented with software serial at some baud rates, and for another a software serial implementation could be a plausible way of overcoming swapped RX & TX wiring, or a way of implementing inverted signalling logic when using simplified level shifters or talking to something which expects to.

Given that in its current location the code is no longer necessarily only for software serial use, it seems plausible that a carefully written and fully validated patch to make it more general might be favorably received.


Cannot make LCD & Gyro work together I'm new to this so there are some poor methods in my code when I try to introduce the LCD into the loop. My issue is that the LCD delay and the servo delay are interfering with each other. How can I isolate them? I like the 50ms response for the servo. But I would like maybe a 200ms refresh for the LCD. But in their current state they are giving a very odd response if I have them both in the loop. The servo is spinning slower as though it's adding both delays. If I disable the LCD it all goes back to normal. Any ideas? Could someone please show me the correct method so I can expand in the future? Thanks!!!!

I've got this so far:

#include<Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

//SERVO
#include <Servo.h>
Servo microservo1;
int servo_pin = 8;

//MAPPED VALUES
int16_t AcXmapped, AcYmapped, AcZmapped;

//LCD
#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
//initializes the library

void setup(){

  //SERVO SETUP
  microservo1.attach ( servo_pin );

  //WIRE SETUP
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(9600);
  Serial.println("Transmission Line Initializing");
  delay(350);
  //print("3"); print("2"); print("1");
  Serial.println("3");
  delay(1000);
  Serial.println("2");
  delay(1000);
  Serial.println("1");
  delay(1000);

  //LCD SETUP
  lcd.begin(16,2); //setup LCD number of columns and rows
  digitalWrite(9,1); //can either go 0 --> 1 or LOW --> HIGH || turns LCD on or off ||
  analogWrite(6,70); //contrast setting for the text on the LCD
}

void loop(){

  //WIRE LOOP
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print(" | AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  //Serial.print(" | Tmp =  "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);

  //MAPPING the values from e.g. AcX to AcXmapped so they're better values for servo control.
  //set the AcX inside the map to negative if you want to invert the rotation of the servo.
  AcXmapped = map (AcX, -17000, 17000, 0, 180); //ROLL
  AcYmapped = map (AcY, -17000, 17000, 0, 180); //PITCH
  AcZmapped = map (AcZ, -17000, 17000, 0, 180); //YAW

  //SERVO LOOP
  microservo1.write(AcYmapped);
  //50 ms response between movements
  delay(50);

  //LCD LOOP
  lcd.setCursor(0,0); //set the cursor to (0,0)
  lcd.print(AcYmapped);
  delay(50);

  //EXTRA LCD
  lcd.noAutoscroll(); //turns off autoscroll
  lcd.clear(); //clears the screen for the next loop

}

First upload the msg errors you've get .
Second the lcd can't display values in realtime because when the gyroscope move the arduino blocking the lcd and reading the data from gyroscope because you using no scheduling coding.
I recommend you to use millis  instead of delays and use  multitasking code like freertos .


Problem while writing sketch for GSM module sim800 I wanted to my GSM to recieve SMSs. I have written a sketch for it. But while verifying the sketch an error pops out in this part:

if (sms.available()) {
      sms.remoteNumber(senderNnumber, 20);
      if (senderNumber == "09432167015") {
        c = sms.read();
      if (c == "yes") {
          alarm_police();
          }
        }
      }
The error message:

  Arduino: 1.6.5 (Windows 8.1), Board: "Arduino/Genuino Uno"

  GuardDog_v2.5.ino: In function 'void loop()':
  GuardDog_v2.5:201: error: 'senderNnumber' was not declared in this scope
  GuardDog_v2.5:204: error: ISO C++ forbids comparison between pointer and >integer [-fpermissive]
  'senderNnumber' was not declared in this scope

  This report would have more information with
   "Show verbose output during compilation"
   enabled in File > Preferences.

I have checked the receiving sms example and have written the sketch according to the example.I need help regarding this error and how to fix it

You misspelled the variable senderNumber. Correct it. Also you aren't reading the SMS properly or comparing the phone numbers properly. Your code should be like this (using the examples):

#define MAX_MSG 50

char senderNumber[20];
char sms_buf[MAX_MSG];   // a buffer for your sms, max len = 50

if (sms.available()) {    // this part should be in loop()
  sms.remoteNumber(senderNumber, 20);
  if (strcmp(senderNumber, "09432167015") == 0) { // compare numbers
    while (sms.available() == 0);   // wait for a char
    char i = 0;
    while (i < MAX_MSG - 1){    // till max len is reached; 1 byte for null
      c = sms.read();
      if (c == '\0')  // assuming the modem terminates sms with null
        break;
      sms_buf[i++] = c;   // write char to the buffer
      while (sms.available() == 0);   //wait for a char
    }
    sms_buf[i] = 0;   // terminate the string, just in case
    if (strstr(sms_buf, "yes") != NULL)  // look for 'yes' in buffer
      alarm_police();
  }
}


Another traffic light project I have a school project, where I'm going to make a traffic light system on a pls. I want to try it out on an Arduino first, just to get the hang of it.

To make it a little bit more advanced than I have found on the internet, I want to make the lights go in "emergency mode" if the green lights in both directions are on at the same time. It will then go into a yellow blink.

My idea is something like this:

// Yellow blinking if fault in the system or operator activates it
int killState = digitalRead(Kill);
int resState = digitalRead(Res);
if (killState == HIGH /*|| greenlights in both directions */) {
 while (resState == LOW;) { // Yellow blink as long as system is not reset
  BLINK();
 }
}

I guess I need a variable or two that tells what state the lights are in, but I'm stuck. Any good solutions out there?

Another thing is the reset button. I haven't put much effort in it, but I want it to go into the starting point.

The link to the complete script can be found here.

For starters, take a close look at this line:

while (resState == LOW;)

That is not the correct syntax. But the real issue is how is this while loop terminated? The value is never set again?

Cheers!


XBEE coordinator WITH or WITHOUT Arduino? I am building a wireless system that has got an Arduino with a XBEE as the 'end user' and I need to acquire data/control that Arduino from a PC graphical interface.
As far as I'm aware there are two options to obtain the communication:

I could use another Arduino with XBEE (coordinator) that is connected to my PC (serial) to control the 'end user'. The code is stored in this Arduino which works as a bypass between PC and XBEE.
I could simply use a XBEE without Arduino (coordinator) connected to my PC to control the 'end user'. The code should be stored within the PC or the XBEE to establish communication and control data transmission to different end users (???)

As I am new to the Arduino world, would you please direct me to the best/easiest solution to obtain such thing?

If you want just to control and receive data from your end user, option 2 is easy to implement.

You can use any programming language that supports serial communication such as python, node.js, etc.

What you have to is to note how your coordinator is recognized by your operating system (in windows as com1 port, unix-like as ttyACM or similar) and open it from your preferred language.

After that, you establish a protocol that should be agreed with your Arduino. For example. Suppose you want to collect data from end user, so, you send a message from the coordinator connected in your PC with a code #data through the serial. When the Arduino receives it, it decodes the message and return something like #d125 where it says it is sending the data and the value is 125 (supposing integer values).

Making sure you already have configured the XBees in the same network by setting Same PAN id and cross setting the destination address of each one so they send packates to each other.

I am supposing you are using AT transparent mode where they just send whatever comes in the serial interface, in this mode they work basically sending chunks of bytes and it is up to you to establish a protocol to provide a good flow of data. In this mode there is no guarantee that your packet will reach the destination. In order to fully extend the XBee usage, you'd need the API mode where all the transmission checks are done.

But for you purpose, AT mode seems enough.


Problem uploading big program to arduino I have an arduino duemilanove with ATmega328.

Been doing several experiments with multiple peripherals

I had no problem uploading at all

But when i try to upload a big program (27,074 bytes (of a 30,720 byte maximum))
it compiles fine, then says uploading...

After some time passes i get this error

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

The board and serial port connections are fine.
Any ideas?

PS: Then i tried to upload the blink example, but i get the same error for some reason
Everything worked fine before i uploaded my "big" program

The sync error is a common issue that doesn't have one simple solution (as shown here)

It means that the computer can't communicate with the processor, but it recognizes that it's there (out of sync). This is probably due to something (a peripheral, stray wire) interfering with the transmission from computer to device.

Solutions that have worked in the past:

Unplugging the Arduino for 30 seconds, then plugging it back in.
Removing any wires connected to Rx and Tx pins during upload.
Soldering components connected to Rx or Tx to the board (in this case, I was using a shield that allowed me to do this)

There are lots of solutions available from different sources on the internet, but I have not come across one that names program size as the reason.


ESP8266-01 Wifi module + Wifi shield not present + ESP8266-01 libraries not working? I have Arduino IDE v. 1.8.13.
I bought an ESP8266-01 module which I want to use in my Arduino-UNO board to send fingerprint registration confirmation (ID) via HttpClient to a xampp server since I dont want to store the fingerprint image in the database.
My ESP connection is as below:

In the serial monitor, my AT commands work well when I connect the module to my wifi using AT+CWJAP="ssid","password".
When I upload my code, which is supposed to connect to wifi, it says WiFi shield not present.
Im new to this, is there anything I am missing?
Thanks in advance.
Here is my code:
#include <ArduinoHttpClient.h>
#include <WiFi101.h>
#include "arduino_secrets.h"
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;

char serverAddress[] = "localhost/bel/arduino/scannerstatus/php";  // server address
int port = 80;

WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;

void setup() {
  Serial.begin(9600);
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to Network named: ");
    Serial.println(ssid);                   // print the network name (SSID);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);
  }

Basically, my uploaded code does not go past the wifi connection stage. Even though the AT commands individually can connect to wifi.
I have tried different ESP8266 libraries and HttpClient libraries but they all seem to not connect to wifi.
Is there any other way to call a php script from arduino without using wifi?

Can you please include some explanation of how the Arduino Uno and ESP8266-01 are connected. You will need to program for the ESP8266 ESP-01 module like shown below,

You will need to write code for the ESP module to connect to the WIFI and listen to its Serial Com Port. The ESP will need to handle the message interpretation & WIFI updating.
The Arduino Uni will not be capable of directly using the ESP-01 module as a WIFI shield. It will need to communicate with the ESP via a serial coms link, you will need to send commands that include instructions & a Message to the ESP from the Arduino.

https://create.arduino.cc/projecthub/jeffpar0721/add-wifi-to-arduino-uno-663b9e - Link to the above image document, this should help explain my concept in more detail
I apologies if my comments above miss the point but with the amount of information provided I don't think I can help further.


ST7789 TFT display only shows a correct image while Arduino reset button is held down - Why? I am trying to get the ST7789 TFT display to work with Arduino. I followed online guides  for connections and am using the fast library fron github and included workbench ino (https://github.com/cbm80amiga/Arduino_ST7789_Fast).
Problem: The program runs and drives the display but the image is corrupt and only partial. I discovered that if I quickly and firmly press the reset button - and keep it pressed down - the image at the moment of reset press suddenly becomes full and good (albeit static because reset is pressed). Ofcourse as soon as I release the reset button the program restarts with the same corrupt image (the pictures below illustrate the issue).

I could not find a description of this particular problem by online searching. Here is what I tried to fix it (all to no avail):

I confirmed all pins are correct as defined in the ino script.
I ensure only the 3.3v power line is used. I have never connected the Vcc to 5 v
I tried with a genuine Arduino UNO as well as a clone - both show the same behaviour.
I used 1k:2k resistor voltage dividers for the data lines, res and DC - these did not help. In fact the display did not work at all with the voltage dividers, only the backlight came on and the screen flickered slightly. I checked that I was getting ~3v in the middle of each divider.
I used two separate ST7789 display boards, bought from two separate sellers on different occasions - both show the same behaviour.

[Edits in response to comments below]

The same behviour occurs when using a sketch that uses the standard Adafruit libraries (as opposed to the fast library linked above).
The same corruption is seen when run on an arduino nano clone. However, with the nano, pressing the reset button shows only a fleeting glimpse of the full image prior to resetting (i.e. holding down the reset button does not preserve a static image on the screen).

Any ideas about what is going on and how to fix it? Thanks.

I found the answer to this problem. After reading multiple web pages / YouTube videos from multiple authors on this device and ~all of them warning you must never connect the Vcc to 5v or it will destroy the display, I found one or two that suggested you could use 5v because in this particular module there is a built-in regulator. So, faced with the thing being useless anyway, I decided to take the plunge and connect the Vcc of the TFT to the 5v pin of the Arduino and - hey presto - it works perfectly (see picture below: note the clear full image without the reset button being held down and also notice the voltage pin of the TFT is now connected to Arduino 5v compared to the pictures in my question).

The picture below shows the back of my TFT display module and, from what I have read, it is the J3Y transistor that is key to the voltage regulation in this module.

I hypothesise that pressing the reset button must have allowed equalisation of the voltages somehow but it is beyond my knowledge to explain it. I tried measuring the 3.3v pin on the Arduino with a voltmeter while holding down the reset button but I could see no change (the TFT module was not in situ for this test so maybe there is some interaction between Arduino and the TFT circuitry during reset).
Please note: I suspect this is a peculiarity of the particular TFT display module I have. Please DON'T run your 3.3v devices at 5v unless you have good reason to believe that they can take it. I only tried this after reading a couple of pages (including the detailed specs on the TFT module seller's listing) that suggested it would be OK with my particular TFT module - your's may be different. But if you have the same problem you see in my question then maybe that is something to consider.
Thanks to those who have responded.


Why Firmata Test doesn't allow me to choose a port? I'm a beginner and, sorry, also I don't speak English very well. However, I'm going to try to explain my problem.
I'm working on Ubuntu 14.04.2 and Arduino Uno R3.
I downloaded Firmata Test binaries for Linux 64 bit, I gave it permissions with chmod 754 <file>. Also I uploaded StandardFirmata from Arduino IDE to the board. Afterwards, I quit Arduino IDE and ran Firmata Test with ./file. But, the Port menu has no items within. I tried restarting the board and the application as well.

What can I do?

I had the same problem until I ran it as:
sudo ./file


Issue with If statement and boolean logic I'm trying to control motor based on rain sensor and my own build anemometer. It should only controlling motor clockwise/CW for open the roof if there are no rain (indicated by value above 900) AND the wind speed below 4 km/h. If there are raining (analog value below 650) and/or wind speed above 4 km/h the motor should spin counterclockwise/CCW. I succeed to rotate the motor CCW if rain and/or high wind speed happen, but when the motor hit the limit switch for stopping the motor, motor only stop for maybe 2 seconds and then back rotating CW (open the roof), even the wind still above 4 km/h. The roof should be open only when there is no rain (analog value above 900) and the wind speed below 2 km/h. Here is my If Statement logic program:

if ((analogRead(rain) < 650 || (Wind > 4)){
  motor_closed();
}

else if (analogRead(rain) < 650 && (Wind > 4)){
  motor_closed();
}

else if (analogRead(rain) < 650 && (Wind < 2)){
  motor_closed();
}

else if (analogRead(rain) > 900 && Wind > 4){
  motor_closed();
}

else if (analogRead(rain) > 900 && Wind < 2){
  motor_open();
}

Did I make mistake when using && boolean operator? Or its something else?


Do I need to power off the Arduino board before doing something? Is it safe to build a circuit while the Arduino board is powered?

Should I power the board only when I have to upload the program?

It is not safe, as you may accidentally connect some points, which should not be connected and destroy Arduino and/or any other part of circuit. typically legs of resistors/LEDs tends to touch other legs near them, when you are putting it in - and if it is powered, magical smoke can happened easily.

Even if you do not this kind of mistake, not everything can be put in random order without risc of damage.

So everytime you change something with circuit, disconnect power source/USB first. And if you have big capacitors anywhere, you better make sure, they are discharged too.

You switch on the board, when the building is done and you want to program it, or use the already present program.


How to integrate nRF24L01 to esp8266 nodeMCU? I can't seem to integrate an nRF module to my nodeMCU.
I just want to verify my code but an error message keeps popping up

Below is the sketch:

#include <SPI_Class.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <ESP8266WiFi.h>
#define PIN_CE D4
#define PIN_CSN D3
RF24 radio(PIN_CE, PIN_CSN);

struct package{
  int id = 1;
  int location = 1;
  char timeStamp = "date/time"
};

typedef struct package Package;
Package data;

public int data1=data.id;
public int data2=data.location;
public char data3=data.timeStamp;

byte  address[][6] = "00001"

const char* ssid = "Jino";
const char* pass = "myinternet";

char server[] = "cdgresearch.000webhostapp.com";

WiFiClient client;

int led = 2;

void setup() {
  Serial.begin(9600);
  WiFi.begin(ssid,pass);
  pinMode(led,OUTPUT);
  digitalWrite(led, HIGH);
  delay(500);
  Serial.println("Connecting to: ");
  Serial.println(ssid);
  Serial.print("Connecting");
  while(WiFi.status() != WL_CONNECTED)
  {

    delay(1000);
    Serial.print(".");
  }

  delay(300);
  digitalWrite(led, LOW);
  Serial.println();
  Serial.println("Successfully connected to the network");
  Serial.print("NodeMCU IP Address: ");
  Serial.println(WiFi.localIP());

  delay(1000);

  radio.begin();
  radio.setChannel(115);
  radio.setPALevel(RF24_PA_LOW);
  radio.openWritingPipe(address[0]);
  delay(1000);
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(9000);
  sendData();
}

void sendData(){
  Serial.println("Sending Data...");
  delay(1000);
  if (client.connect(server, 80)){
    WiFi.printDiag(Serial);
    Serial.println("Connected to server");
    client.print("GET /tag2.php?");
    client.print("incoming=Id ");
    client.print(data1);
    client.print("&incoming2=Loc");
    client.print(data2);
    client.println(" HTTP/1.1");
    client.println("Host: cdgresearch.000webhostapp.com");
    client.println("Connection: close");
    client.println();
    Serial.println();

    while(client.connected()){
      while(client.available()){
        Serial.write(client.read());
       }
      }
    radio.write(&data,sizeof(data));

    Serial.print("\nPackage: ");
    Serial.println(data1);
    Serial.print("Location: ")
    Serial.println(data2)
    Serial.println(data3)
    data1+=1;
    data2+=1;
    delay(1000);

  }

  else{
    Serial.println("Failed to Connect to server...");
    }

  client.stop();
  Serial.println("Disconnected from Server");
  while(client.status()!=0){
    delay (10);
   }
  }

and this error comes up in the console:

even if I use the #include, still this pops out

Your error is: .../packages/esp8266/hardware/esp8266/2.4.2/libraries/SPI/src/SPI.h:1:23: fatal error: SPI_Class.h: No such file or directory...

You have some wrong SPI library there. The original folder packages/esp8266/hardware/esp8266/2.4.2/libraries/SPI doesn't contain src subfolder.


ESP32 CAM failed to get frame in time So I think the title says it all. I recently purchased an ESP32 CAM in India for a pretty cheap price.

It looks like an AI Thinker but doesn’t have the tag on the chip itself. Nonetheless, to get it setup before my use case I decided to test the camera. I loaded up the CameraWebServer example and set my camera type to AI thinker.

The code uploads successfully and runs successfully. I can open up the IP address and it shows the page. However whenever I try to get a still or start a stream, it gives this error:

[E][camera.c:1344] esp_camera_fb_get(): Failed to get the frame on time!
Camera capture failed

It’s pretty annoying and this happens in both 5V power and 3V power. The camera does physically get a bit hot after loading the website. Oh yeah, I have an OV 2460 Camera attached to the ESP.

Any advice is appreciated. Thanks!

Solution for if this occurs on a known working ESP-32-cam with PSRAM (i.e. example sketch with face recognition works ok).
If you're using anything other than PIX_FORMAT_JPEG, try reducing xclk_freq_hz.
In my case, it suddenly worked fine with PIX_FORMAT_RGB888, FRAMESIZE_VGA and xclk_freq_hz = 5000000 (4x lower).
( @Vraj P, this might not apply directly to what you found your problem was, but this post gets seen by many searching for this problem. Thanks!).


Hardware to measure velocity via string/wire attatchment? beginner This is a broad question but I want advice on what type of hardware I should look for to make a device that could measure the velocity of an object attached via a string/wire to some sort of rotary wheel.

The purpose of this is to attach it to a barbell and measure mean-velocity for weightlifting atheletes.

I'm a software engineer by trade but know nothing about hardware. I will obviously need to start with simple projects to learn, but I would like to know which hardware I should lean towards buying, so I don't have to re-buy anything?

This is an example of the optical encoder.
You want to use interrupt detection, rather than polling.
Or maybe even an HW counter.
That's all you really need.

I am using 4 of them for a car.

I am in the process of refactoring the code, but you could already have a look at the driver & example I wrote for ChibiOS, here.


What is the difference between Nano 328p-au and 328p-mu? What is the difference between Nano 328p-au and 328p-mu? Does it have to do with the updated bootloader or is it just a different board design? I want to make sure I order the correct one and I could not find a proper answer so far. Thanks.

The AU and MU on the chip just refer to the shape of the chip. AU is TQFP and MU is VQFN.

You can see the full list of suffixes here (select the red "Buy Now" tab for a table).


ESP8266 and Arduino integration I am trying to upload a sketch and getting below error:

error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed.

Connections:

TX - TX
CH_PD - 3.3 V
RX - RX
VCC - 3.3
GPIO GND
GND - GND

Before uploading the sketch I have reset the arduino and ESP and selected board as ESP8266 and baud rate as 115200 but still getting the same error.

You don't say what you're using to program it (an FTDI board? the USB adapter on an Arduino?) but you probably want to connect

TX - RX
RX - TX


Is it bad coding practice to design a buffer using pointers? I coded a ring buffer for my Arduino to buffer data from either the SPI or TWI ports. In the .h file I used a pointer for the buffer:

typedef uint8_t *ring_buffer_t;
typedef uint8_t ring_count_t;
typedef uint8_t ring_index_t;
typedef uint8_t ring_size_t;

typedef struct ring_t
{
    ring_buffer_t buffer;
    ring_count_t  count;
    ring_index_t  head;
    ring_index_t  tail;
    ring_size_t   size;
}rint_t;

int ring_init(ring_t *r, ring_buffer_t buffer, ring_size_t size);

// other function prototypes to add and remove from the ring buffer

There is more code to handle adding and removing from the buffer, but I am simplifying here. Then in my .c file I have:

#include<string.h>

void ring_init(ring_t *r, ring_buffer_t buffer, ring_size_t size)
{
    r->buffer = buffer;
    r->size   = size;
    r->head   = 0;
    r->tail   = 0;
    r->count  = 0;

    // clear out the buffer memset cheaper by 12 bytes rather than for loop
    memset((void *)r->buffer, 0, r->size);
}

Then somewhere in code where the ring buffer is going to be used:

In SPI.h ...
#define MAX_BUFFER_SIZE 32
ring_t  rx_ring;
uint8_t spi_rx_buffer[MAX_BUFFER_SIZE];

#define MAX_BUFFER_SIZE 32
ring_t  tx_ring;
uint8_t spi_tx_buffer[MAX_BUFFER_SIZE];

In SPI.c ...
void spi_init( ... )
{
    ring_init(&rx_ring, spi_rx_buffer, MAX_BUFFER_SIZE);
    ring_init(&tx_ring, spi_tx_buffer, MAX_BUFFER_SIZE);

    // initialize other spi parameters
}

Are there any issues with my code that are obvious that I am not seeing? I ask because I ran the code and it works, but I feel I am doing something wrong. I can code in C and remember something about malloc() for dynamic memory allocation, just not sure if what I am doing qualifies. Or should this work creating a buffer of some defined size?

Thanks for any help or ideas.

EDIT: 07/27/2014 Added code to try and make what I am trying to do clear. Let me know, thanks.

Don't bother with malloc unless you need to. If you explicitly define your buffer before hand then you can use avr-size to check your SRAM usage.

Also the C compiler automatically adds code to initialise global variables to 0, so you don't need ring_init if your define the array explicitly. See https://stackoverflow.com/questions/2218254/variable-initialization-in-c for initialisation comments. Even if buffer was filled with non-zeros it wouldn't matter because it should be written to before being read from.

If you change the ring buffer from chars to ints, etc. you will have to change memset, as it assumes chars.

Will MAX_BUFFER_SIZE change? If not, you could put the buffer in ring_t.


How to send a number to Arduino via Python over serial? I call an API in Python and it gives as output as a single digit and an Arduino program receives this number over serial and displays it on a 7-segment display.

I wrote a different program in which Arduino sends the data and a Python program receives it. That worked but the following program is not working. What is the problem?

I am using Python 3 and Arduino Uno.

Python program:

import serial ,requests, json, time
arduino = serial.Serial('COM1', 9600, timeout=.1)
time.sleep(1)
response = requests.get("https://traffic.cit.api.here.com/traffic/6.1/flow.json?bbox=12.9808%2C77.5759%3B12.9803%2C77.5767&app_id=zbvY0tdRs089c3ZTKqWR&app_code=pxAtGksNBgVD9V5XF5nEzA",)
#CALLING API
response.content.decode("utf-8")
data = response.json()
text = str(data) #CONVERSION TO STRING
l = len(text)
for i in range(0,l): #Taking out the number
    if text[i] == 'J':
        j = text[i + 5]
        print (j)
        arduino.write(j) #writing over serial
        break

Arduino program:

int a=2;
int b=3;
int c=4;
int d=5;
int e=6;
int f=7;
int g=8;
int h=9;
int rx_byte = 0;

void setup() {
  Serial.begin(9600);
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(e, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(g, OUTPUT);
  pinMode(h, OUTPUT);
  digitalWrite(h, 0);  // start with the "dot" off
}

void loop() {
  if (Serial.available() > 0) {
    rx_byte = Serial.read(); //reading serial
    switch (rx_byte) {
    case 0:
      zero();
      break;
    case 1:
      one();
      break;
    case 2:
      two();
      break;
    case 3:
      three();
      break;
    case 4:
      four();
      break;
    case 5:
      five();
      break;
    case 6:
      six();
      break;
    case 7:
      seven();
      break;
    case 8:
      eight();
      break;
    case 9:
      nine();
      break;
    }
  }
}

// write '9'

void eight() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 1);
  digitalWrite(f, 1);
  digitalWrite(g, 1);

}
void seven() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 0);
  digitalWrite(e, 0);
  digitalWrite(f, 0);
  digitalWrite(g, 0);

}
void six() {
  digitalWrite(a, 1);
  digitalWrite(b, 0);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 1);
  digitalWrite(f, 1);
  digitalWrite(g, 1);
}
void five() {
  digitalWrite(a, 1);
  digitalWrite(b, 0);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 0);
  digitalWrite(f, 1);
  digitalWrite(g, 1);

}
void four() {
  digitalWrite(a, 0);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 0);
  digitalWrite(e, 0);
  digitalWrite(f, 1);
  digitalWrite(g, 1);
}
void three() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 0);
  digitalWrite(f, 0);
  digitalWrite(g, 1);

}
void two() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 0);
  digitalWrite(d, 1);
  digitalWrite(e, 1);
  digitalWrite(f, 0);
  digitalWrite(g, 1);
}
void one() {
  digitalWrite(a, 0);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 0);
  digitalWrite(e, 0);
  digitalWrite(f, 0);
  digitalWrite(g, 0);

}
void zero() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 1);
  digitalWrite(f, 1);
  digitalWrite(g, 0);

}
void nine() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 0);
  digitalWrite(e, 0);
  digitalWrite(f, 1);
  digitalWrite(g, 1);

}

I am quite new to programming. Please help.

The python code

j = text[i + 5]
print (j)
arduino.write(j)

Is sending a single text character between '0' and '9', ascii values 48 to 58.

The c code

rx_byte = Serial.read(); //reading serial
switch (rx_byte) {
  case 0:

is looking for absolute values between 0 and 9.

There are two easy options to fix this, option 1 change the case statement to look for the correct values:

rx_byte = Serial.read(); //reading serial
switch (rx_byte) {
  case '0':

or option 2, rely on the fact that the ascii for the numbers is always 48 more than the number represented and subtract that:

rx_byte = Serial.read() - '0'; //reading serial
switch (rx_byte) {
  case 0:

-'0' and -48 would have exactly the same effect here only by using '0' it makes it clear we are offsetting by the ascii value of a 0 rather than by some other randomly created number. It also saves you having to remember what the correct value is for 0.

Generally since you are using the value in a case statement I'd recommend the first option, it's a little more intuitive and avoids an extra calculation that can look a little odd if you are new to programming.
The reason I mentioned the second option is that this is the method you would use if you wanted to use the rx_byte value as the index in an array for any reason.


How do I Read and Write data from a USB stick? Hello I have an Arduino Uno and I salvaged a USB port from an old computer. The USB port has 4 pins on it and it accepts USB sticks. I was wondering if it is possible to connect it to my Arduino so my Arduino can load data from files on the USB. I don't want to go out and buy a shield but I don't mind using libraries. Is it possible to read and write data from a USB stick with Arduino?

The Uno does not have any USB host or OTG capabilities on its own, and bit banging it is not easy. A USB Host shield, or a better microcontroller is needed.


Arduino sizeof Servo array objects is.. wrong? After searching for a quite long while over the internet, I have no choice but to try asking someone if they can explain me this apparently strange situation.

I'm doing some tests using some servo motors, trying to move them almost together using millis() and Servo object.

It is, of course, working either for single Servos and multiple servos.

The case, more detailed, is about this:

Move one, two or more servo motors together.
Force them to take ALMOST the same time to accomplish any action.
Have a dynamic number of servos.

About the first two points I had no problems to solve them, I was easily able to make a function and then make a library to accomplish such a job.

However, since I'm NOT that used to C++ and I was wondering if it actually was possible to create an array of Servo objects, like you can actually do, on arduino, with strings:

String stringArray[] = {"string1", "string2", "and so on, I love it."};

So, after wondering a while, I've tried this:

Servo servObject;
Servo servObject_2;
Servo servObject_3;

Servo servos[] = {servObject, servObject_2, servObject_3};

And you know what's cool? my function is actually working correctly by forcing the amount of elements of the servos array.

What I mean by that is that if I force my function to know that it is going to have 3 elements into the array it will, of course, work; However, for some reason, if I use sizeof(servos); the value returned, surprisingly, is 2....
Moreover, if I only push two servo objects instead of three into the servo array, its sizeof returns 6.

By googling, I've found out a couple of discussions about the fact that, for some reasons, in some cases, sizeof returns an incorrect value (if I'm not wrong it was the correct value -1), but in my case it apparently is not following any logic at all.

The board I'm using is an Arduino nano w/ ATMEGA 328.

Any idea of why it is not returning the correct value? Am I actually going totally wrong because I shouldn't make an array of servo objects?

ps: I didn't post the whole code because it would've been useless, since the sizeof is the first function called in the loop()

Regards,

briosheje

What you describe seems to be a common issue that many C or C++ developers can get (or have got) with sizeof.
Take a look at the following code:
char a[3];

int size(char b[]) {
    return sizeof b;
}

void setup() {
    int size1 = sizeof a;
    int size2 = size(a);
}

In that code, size1 will be evaluated, by the compiler, to 3 which is the real size of a variable, whereas size2 will be 2.
Why so?
This is just because sizeof a is evaluated by the compiler, and the compiler knows that a is an array of 3 char; but when a is passed as an argument to function size(), it is converted to a pointer (to the first element of the array), hence its size is the size of a pointer, which is 2 bytes on AVR ATmega MCU.
This subtlety of sizeof may explain strange values as you describe.
How to fix the issue?
Most C functions that take an array as argument will require another argument that tells the size of the array; that's the way (the only one I think) to deal with this problem.
Here is a sample code:
Servo allServos[] = {...};
#define NUM_SERVOS (sizeof(allServos) / sizeof(Servo))
...
void handleServos(Servo *servos, int numServos) {
    for (int i = 0; i < numServos; i++) {
        servos[i].write(...);
        ...
    }
}

void loop() {
    handleServos(allServos, NUM_SERVOS);
}

It is common practice in C to declare an array and immediately after, define its size as above.


Over voltage protection for Arduino If an external voltage of 7 volts is applied to the external voltage input on the Arduino and the power from the USB port remains connected, is there a protective circuit that will protect the Arduino?  Thank you.

yes there is. power will be drained from external source(altough 7 volts is around the limit and arduino may switch to usb power) and arduino will still operate at 5v, same as usb. in any case your arduino and usb will be safe.


Ways of communication between two Arduinos? I have two circuits one having a ultra sound sensor and one other having a relay module. So i'm trying to establish communication between the two to send and recieve data. I just want to know which way is the best so that one arduino will send data only when the other is powered and able to recieve data. So that there is no problem when one circuit is powered on and the other is not and the data is not sent until the connection between the two is established .This is because the circuits are powered by different power sources and the current is not predictable and i dont want any miscommunication happening between them.
any way is okay like rf or wifi or some other methods? Using other devices is also an option like ESP32 which has builtin wifi and bluetooth, But wired is not possible because the distance is too big like about 15-17 meters and using the same power source is not viable for the same reason. Tell me also if the distance im worried about is not a problem?

Let the ultrasound-module broadcast measurements and not care about whether anyone are listening or not. If you are using wifi, you can send to the broadcast address of the network you are using. Then the ultrasound-module does not need to know anything about the receiver, like ip address or number of receivers. The only thing you need to make sure is that they are on the same subnet. If you want to, you can later put another module on the same subnet and it will also receive the data.
If you establish a handshake protocol it complicates things, because there are so many cases you need to consider. What should happen if communication link dies after handshake, but before data are transmittet? Should the receiver acknowledge the data? What should the sender do, if it does not receive the acknowledge? etc...
If the only thing the sender is using the handshake for is to know whether to send data or not, then just send it and forget about it. If it was to do something special, in case there are no receiver, like logging data and send the log when the receiver comes back online, then there is a use case for the handshaking.


Comma between two values in a macro I am working on a project involving an Aduino and screen.

As i was going through the u8glib (Arduino Monochrome Graphics Library for LCDs and OLEDs), something caught my attention:

#define U8G_ESC_DLY(x) 255, ((x) & 0x7f)
#define U8G_ESC_CS(x) 255, (0xd0 | ((x)&0x0f))

How can i interpret this macro for a given x value ?

How can i interpret this macro for a given x value ?

As normal. First expand the macro, and then worry about what the comma means in context. In an expression the result is the expression on the right of the comma. In a function call it stands in for two arguments. Just look at where it's used and that's what it will mean.


AD9833 Breakout Short I recently bought a breakout board for an AD9833 waveform generator, but discovered pretty quickly that VDD and GND were shorted out. Assuming that there must have been some manufacturing defect, I checked the board over but could see nothing unusual. I got hold of a replacement module and exactly the same issue presented itself. I simply can't figure out what the problem is. Does anyone know of an issue with these boards, or am I just missing something blindingly obvious? Any thoughts much appreciated.

Thanks for the responses. I discovered the short initially by connecting power from an Arduino and seeing the Uno's LED turn off. I then tested with a DMM and confirmed the short. Thinking that I could have damaged the module, I got another one and this time tested with a DMM first, with the same result. The resistance reads as 0.4 ohms (the resistance of my probes) so I am convinced that it is a dead short. I've checked the soldering carefully and can see no bridges etc. This was admittedly a cheap product from eBay, but I'm surprised that two in a row had the same issue. I could just buy a different version, but this type seemed the most convenient for prototyping.
Pictures as requested:

I was going to post this as a comment, as it is by no means a definitive answer, but I wanted to include the schematic to help the OP understand what may be happening. When the OP provides further information, I will edit/delete as appropriate.

Without additional information, it is difficult to answer your question:

As Jot asks, how did you determine that you have a short?

Did you test for continuity between VCC and GND, using a DMM?
Or did you encounter the short by connecting to a power supply and blowing a fuse?

If you did perform a check of the resistance between VCC and GND, using a DMM, what was the value that you obtained?
Is it possible that what you think is a short, could be simply a temporal charging of the capacitors by the DMM (if that is what you used to determine the short)?

Here is a schematic of your board, which may help:


Arduino whack-a-mole game not working Everyone, I am new to this. Currently I am trying to make a Whack-a-mole game for my school project. There will be a total of 6 moles (corresponding to 6 LEDs, which will light up randomly). At each moment, there will only be one LED lit up. The whole game duration is 30 seconds. At the end of the game, the score will be displayed.

I use a piezo electric sensor to detect the knock of the user. I program it in such a way that if the reading of the piezo sensor is greater than 50, it will take it as knock, and if the user knocks it correctly, one point will be awarded.

But unfortunately my code isn't working. The score displayed appears to be random numbers, doesn't work as it is supposed to be.

Here is my code, please hep me to have a look and provide me with some guidance. Thank you.

unsigned long time_since_reset;
int previousNum=0;
int currentNum =0;
int randomGenerator (void);
void light(int port);
int checker(int port);
int score =0;

void setup() {
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  time_since_reset = millis();
  while((millis()-time_since_reset)<30000) {
    randomSeed(analogRead(0));
    currentNum = randomGenerator();
    light(currentNum);
    checker(currentNum);
  }
  Serial.println("End Game");
  Serial.println(score);
}

int randomGenerator(void) {
  int cNum;
  cNum = random(3, 8);
  if(cNum!= previousNum) {
    return cNum;
  }
}

void light(int port) {
  digitalWrite(port,HIGH);
  delay(1000);
}

int checker(int port) {
  jump:
  int mole1 = analogRead(0);
  int mole2 = analogRead(1);
  int mole3 = analogRead(2);
  int mole4 = analogRead(3);
  int mole5 = analogRead(4);
  int mole6 = analogRead(5);
  while(mole1<10 && mole2<10 && mole3<10 && mole4<10 &&mole5<10 &&mole6<10) {
    goto jump;
  }
  if(mole1>50 && port == 3) {
    score++;
    digitalWrite(port, LOW);
  }
  if(mole2>50 && port == 4) {
    score++;
    digitalWrite(port, LOW);
  }
  if(mole3>50 && port == 5) {
    score++;
    digitalWrite(port, LOW);
  }
  if(mole4>50 && port == 6) {
    score++;
    digitalWrite(port, LOW);
  }
  if(mole5>50 && port == 7) {
    score++;
    digitalWrite(port, LOW);
  }
  if(mole6>50 && port == 8) {
    score++;
    digitalWrite(port, LOW);
  }
}

The code as shown has a bunch of problems; the probably-most-important are as follows.

• score is not initialized.  Add score = 0; after
 time_since_reset = millis();

• As noted in a comment, the delay(1000) statement in light() prevents checking for whacks during the first second of a light being on.  This probably is undesirable – most people expect to whack a mole much sooner than a second after it appears.  If you want a delay there, make it at most 20 milliseconds. [See edit 2]

• The sequence randomSeed(analogRead(0)); currentNum = randomGenerator(); has a good chance of generating the same value of currentNum several times in a row, which may result in multiple counts for a given whack.

• Instead of saying randomSeed(analogRead(0)); within the inner loop, say it just after time_since_reset = millis(); or (probably better) in setup().  If analogRead(0) changes slowly, the same random seed may get used over and over, resulting in the same sequence of numbers from the random(3,8) expression.

• Your randomGenerator() routine has undefined behavior:  It doesn't return a valid result if the current random  number is the same as the previous one.  You could add a loop that calls random() again if the value is the same as before; but not returning a value results in  undefined behavior.

Edit 2:  When you turn a light on, record the current millis() time reading, say in onTime[i] for light i, and set flag isOn[i] true.  Later, when isOn[i] && (millis()-onTime[i] > targetDelay[i]), turn the light off and clear the flag (via isOn[i] = false).  Within checker(), a condition like port == 6 translates to isOn[6], an expression which is true when light 6 is on, else false.

The approach of using arrays like onTime[] and isOn[] and targetDelay[], variable subscripts, and recorded on-times has several benefits:  It lets you loop through lights, getting rid of that needlessly repetitious code in checker(); it enables other processing in the main game loop (such as whack-testing) to proceed independently of light control; it allows multiple moles to pop up at the same time; and it allows different moles to have different or varying up times.


4x4 matrix keypad - Multiple inputs cause extra readings I have the following matrix keypad -

I am using this as a sort of controller with my Arduino (Mega2560) but I can't get real multiple inputs to work. I am able to have say two individual keys pressed at a time but after that they overlap with eachother. (Using the Keypad library also).

Here is an illustration of the issue:

If I press the 3 blue buttons and use the getKeys function it thinks that the red one is also pressed. This works when any three or more buttons are pressed that produce a square.

I have a post about keypad matrices which discusses this issue. The issue with keypads is, that if you don't install diodes, if three keys are pressed the current finds its way around those three keys and it looks like a fourth is pressed.

If you install diodes, like this, the issue goes away:

It can be a little tedious to do, but I managed it the other day with surface mounted diodes.

The above board is different from yours, mine is one with soft switches which I could lift off to get at the board.

Yours looks like it might be almost impossible to cut the tracks and install the diodes. Without them you can press two keys at once without issues. Perhaps that is enough. :)


Using the YS-IRTM with an Arduino Uno Picked up a YS-IRTM IR Transmitter/Receiver module to do some testing for a project. There's not a lot of details on it but eventually came across two very important sources:

Translated Module Datasheet: https://docplayer.net/101050357-Nec-infrared-codec-module-ver1-0-ys-irtm.html

Examples: https://forum.arduino.cc/index.php?topic=359707.msg2861077#msg2861077

I've been trying to get this working for a few days and so far haven't gotten anything. Need to reach out before I pull out whatever hair I have left.

BTW, new to this and may have easily missed something.

Wiring Diagram

Arduino Uno    YS-IRTM
5v          -> 5v
GND         -> GND
0 RX        -> TXD
1 TX        -> RXD

Code

int icb = 0;
SoftwareSerial ir_mod(0, 1);

void setup(){
  Serial.begin(115200);
  while(!Serial){}
  Serial.println("Setup IR Serial");
  ir_mod.begin(9600);
  while(!ir_mod){}
  Serial.println("IR Serial Ready");
}

void loop(){
  if(ir_mod.available() > 0){
    icb = ir_mod.read();
    Serial.print(" 0x");
    Serial.println(icb, HEX);
  }
}

Current Output

Setup IR Serial
IR Serial Ready

Nothing will happen if I try to interact with the Receiver with any IR Transmitter (like a TV/AC Remote) but if I disconnect and reconnect the power, I get " 0xFFFFFFFF". Then nothing.

Default baud for module is 9600 unless you previous set it diffrent as per the datasheet A1 F3 ## 00 00 I believe


Permanent connections with Arduino Due The Arduino Uno (for some models) has the ability to dislodge its IC chip. You can mount this on a piece of perfboard and, in essence, have a permanent connection. I will need the beefier Arduino Due, but I do not know how to make permanent connections with this device. Is there any way to form some kind of permanent connection with this board?

What it sounds like you want is an Arduino Due footprint prototyping shield.

Arduino make one, although it is out of stock, but it gives you an idea of what you are looking for. There are plenty of other designs out there for purchase of varying degrees of complexity.

You solder the pins in place and mount it on top of your Due just like any shield, and solder your wires and components in where you want them.

An alternative option, of course, is to step away from Arduino and investigate some of the many other chips from other manufacturers out there that are considerably more powerful than the 8-bit ATMegas used on the low-end Arduinos, and yet are still available in a DIP footprint - chips like the PIC32MX1xx/2xx series from Microchip - 28 pin DIP (just like the 328P) yet 50MHz, 32-bit power.  Yes, it will be a bit of a learning curve, but there are helpful options out there that can assist you, like the chipKIT system including the handy DP32 board from Digilent.


Gas Sensors with Arduino + Interfacing Circuit I am intended to use Gas Sensors (MQ series) on protoboard so I connect it to Arduino and perform analogue read.
I would like to request if possible to get the interfacing circuit (resistors, amplification.. etc.) or if there are schematics available.

Also, when I read the data digitized into 10bits ADC value, how can I convert it into units (ppm)?

Thank you so much in advance.

You can connect the directly to the Arduino +5, Gnd and Signal.

I don't know of any calibration data for the sensors that I have.  I suppose you could take the maximum concentration the sensor can measure and divide this by 1024, but I don't know if the value returned is linear or logarithmic.
The data sheet does have some info on, but this page may be more helpful
http://forum.arduino.cc/index.php?topic=230945.0

Oh and don't forget the warm up time on the sensors!


Get production count for current minute I am trying to make a production counter for a machine. I want to display production count of the last minute for each seconds. So, display should update every second and should display real value of last 60 seconds.  I have a system for detect real-time product output and get it to the Arduino using digital input pin.
I wrote below codes and for that.
what I have done is count output and get output per second. Then store it on an array as separated value for each seconds. Every second the array updated and added new value for current second. At last add all count value of last 60 seconds and output as production rate of current minute.
My question is, Is there any easy and efficient way for do this without using few variables ?
    #define countSensor 8  //count sensor input

    uint8_t records[60];
    uint8_t countSensorState = 0;
    uint8_t totalCount = 0;
    uint8_t countOfLastSec = 0;
    uint8_t lastCount = 0;
    uint8_t lastMinCount;
    uint32_t preMills = 0;

    void setup() {
      Serial.begin(9600);
      //init sensor input pin
      pinMode(countSensor, INPUT_PULLUP); //change according to sensor type

      //clear random value of memory locations
      for (int i = 0; i < 60; i++) {
        records[i] = 0;
      }

    }

    void loop() {
      //get count at falling edge
      if (digitalRead(countSensor)^ countSensorState) {
        if (!digitalRead(countSensor)) {
          totalCount++;

        }
        countSensorState = digitalRead(countSensor);
      }
      //get count of last second
      if (millis() - preMills > 1000) {
        preMills = millis();
        countOfLastSec = totalCount - lastCount;
        lastCount = totalCount;
        //record last 60s counts
        //--shift back a second in the array
        for (int i = 0; i < 59; i++) {
          records[i] = records[i + 1];
        }
        //--record current second in array at 59th index
        records[59] = countOfLastSec;
        //get last 60s count
        for (int i = 0; i < 60; i++) {
          lastMinCount += records[i];
        }
        Serial.println(lastMinCount);
      }

    }

As I said in a comment, if you really need to compute that moving sum,
you absolutely need to store the last 60 one-second counts in memory.
That being said, there are a few small issues with this code for which I
would have some suggestions:

There is no point in storing totalCount. You do not really use it,
and it will eventually overflow.

You do not need to explicitly initialize all globals to zero, as that
is implicitly done by the runtime: it is a requirement of the
language.

Your are calling digitalRead(countSensor) three times in a row. The
logic for counting edges is sound as long as the three calls yield the
same result, but that is not guaranteed. It is safer to only read the
pin once per loop iteration.

Similarly, the two calls to millis() can yield different results,
and that will make your timings slightly off.

The condition millis() - preMills > 1000 will only fire when
1001 milliseconds have elapsed. Because of the way millis() works,
sometimes you will miss the 1001th millisecond, and process on the
1002nd millisecond. In order to avoid accumulating these small timing
errors, it is best to update preMills by always adding exactly 1000.

As pointed out by jsotola, you do not need to shift the array: you can
instead reuse the array cell that holds the data you do not need
anymore.

You do not need to perform the whole sum every time. You can instead
update the previously computed sum by removing the count of the second
that falls off the current one-minute window, and adding the count of
the current second.

Here is my attempt at applying all the above suggestions. Warning: it
has not been tested.
const uint8_t countSensor = 8;

uint8_t record[60];       // last 60 one-second counts
uint8_t currentIndex;     // current index in record[]
uint8_t oldSensorState;   // previous state of countSensor input
uint32_t previousSecond;  // last time we printed minuteCount
uint8_t thisSecondCount;  // count of items in the current second
uint16_t minuteCount;     // count of items in the last minute

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

void loop() {
    // Count falling edges.
    uint8_t sensorState = digitalRead(countSensor);
    if (oldSensorState == HIGH && sensorState == LOW) {
        thisSecondCount++;
    }
    oldSensorState = sensorState;

    // Update stats every full second.
    if (millis() - previousSecond >= 1000) {
        previousSecond += 1000;

        // Update minuteCount by removing the second that falls off
        // the window and adding the one that enters the window.
        minuteCount += thisSecondCount - record[currentIndex];

        // Replace the count that is not needed anymore by
        // the current one.
        record[currentIndex] = thisSecondCount;

        // Start counting a new second.
        thisSecondCount = 0;

        // Update current index, wrapping at 60.
        if (++currentIndex >= 60) {
            currentIndex = 0;
        }

        Serial.println(minuteCount);
    }
}


Arduino and MatLab with OWI Robotic Arm Edge -- Issue with I2C I'm working on a project where I want to be able to program a robotic arm in Arduino using MatLab. I've used the Arduino Uno with an Adafruit Motor Shield V2.3 and the OWI Robotic Arm Edge kit. The arm is perfectly assembled and works just fine with the standard remote it comes with. All of the connections with the Adafruit Motor Shield are correctly placed, and the shield has been soldered onto pins that connect to the Uno.

I am absolutely positive that the physical and electronic setup is correct. However, whenever I try to move the motors attached to the shield, none of them register. Below is my code:

a = arduino('COM3', 'Uno', 'Libraries', 'Adafruit\MotorShieldV2')
shield = addon(a, 'Adafruit\MotorShieldV2')
addrs = scanI2CBus(a,0);

dcm = dcmotor(shield, 1);
dcm.Speed = 0.01;
start(dcm)

dcm2 = dcmotor(shield, 2);
dcm2.Speed = 0.2;
start(dcm2)

dcm3 = dcmotor(shield, 3);
dcm3.Speed = 0.2;
start(dcm3)

dcm4 = dcmotor(shield, 4);
dcm4.Speed = 0.2;
start(dcm4)

I believe the issue is with the third line:

addrs = scanI2CBus(a,0);

When I run the code, the shield has the following properties:

shield =

motorshieldv2 with properties:

          Pins: A4(SDA), A5(SCL)
    I2CAddress: 96 (0x60)
  PWMFrequency: 1600 (Hz)

So while the I2C address should be 0x60, the actual value of the addrs variable is a 2x1 cell instead of 0x60, as the project demands/specifies as seen in the workspace:

I'm almost certain that this is the reason behind why none of the motors are being registered, but how can I fix it?

Thanks in advance for any assistance! Please let me know if I need to supply more information.

The documentation in MATLAB for scanI2CBus() notes that the return is a cell array of character vectors

They even give the example:

a = arduino('COM9');
scanI2CBus(a,1)

with result:

ans =
            '0x48'

It appears you will need to parse the cell array into the numeric value or otherwise convert it to a number, perhaps using the MATLAB function hex2dec('hex_value')


Servomotor losing its connection right after being connected to Arduino I am working with two servomotors and both are having the same problem: right after i connect them to the arduino and upload the code, they do as the code says for a really small amount of time (0.1s maybe), and then they simply stop. If i keep connecting and reconnecting it again the servo answer to the code for a really small amount of time and then stop, as I said before.

#include <Servo.h>

#define SERVO 6 // Porta Digital 6 PWM

Servo s; // Variável Servo
int pos; // Posição Servo

void setup ()
{
  s.attach(SERVO);
  Serial.begin(9600);
  s.write(0); // Inicia motor posição zero
}

void loop()
{
  for(pos = 0; pos < 90; pos++)
  {
    s.write(pos);
  delay(15);
  }
delay(1000);
  for(pos = 90; pos >= 0; pos--)
  {
    s.write(pos);
    delay(15);
  }
}

I am using the code above, and it looks totally fine. Does anyone know what might be causing this problem?

Your code is correct. Check the following:

Arduino works from 5V, but most servos need 6V.
Even if your servo works from 5V, don't ever connect your servo power directly to Arduino pins. These pins are not able to provide adequate power for servo.
Check that grounds of both power supply for Arduino and power supply for servo are connected together.