How can I stock data, and send them over by serial? I want to make an array with data from the sensor. In data, I have displacement in x/y axis. I want to send them in the array, because in my python code I don't send them one by one, slow down really quickly program.

Arduino code responsible for sensor

class MouseRptParser : public MouseReportParser
{
protected:
 void OnMouseMove (MOUSEINFO *mi);
};

void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{

    Serial.print(mi ->dX, DEC);
    Serial.print(",");
    Serial.println(mi ->dY, DEC);

};

I tried to do something on my own, but I get stuck with an error about data not in the scope. I try some variant placing it, but I don't succeed .

class MouseRptParser : public MouseReportParser {

 void OnMouseMove (MOUSEINFO *mi); };

void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{ int i;   for (i=0;i<10;i+2)   {
        data[i]=(mi ->dX, DEC);
        data[i+1]=(mi ->dY, DEC);   }
  Serial.println(data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7],data[8],data[9]);

    delay(20); };

EDIT:  I have now program that's making an array of 10 cells, but values in it are constatnt 10.

#include <hidboot.h>
#include <usbhub.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
int data[10];

class MouseRptParser : public MouseReportParser
{
protected:
 void OnMouseMove (MOUSEINFO *mi);
};

void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{

    for (int i=0; i<10; i=i+2)
  {
    data[i]=(mi->dX, DEC);
    data[i+1]=(mi->dY, DEC);

  }
  for(int j=0; j<10; j=j+1)
  {
  Serial.print(data[j]);
  Serial.print(",");
}
Serial.println();
  delay(100);
};

USB     Usb;
USBHub     Hub(&Usb);
HIDBoot<USB_HID_PROTOCOL_MOUSE>    HidMouse(&Usb);

MouseRptParser Prs;

void setup()
{
    Serial.begin( 9600 );
#if !defined(__MIPSEL__)
    while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
    //Serial.println("Start");

    if (Usb.Init() == -1)
        Serial.println("OSC did not start.");

    HidMouse.SetReportParser(0, &Prs);
}

void loop()
{

  Usb.Task();

}

There is no such thing as "all at once" with serial. The whole point of serial is that it sends things one character at a time.

It is entirely up to you to decide what constitutes one "block" of data.

There is absolutely no difference (besides some slight processing overheads) between:

Serial.print("Hello");
Serial.print(" ");
Serial.println("World");

and:

Serial.println("Hello World");

Both of them result in Serial sending:

H
e
l
l
o
[space]
W
o
r
l
d
[cr]
[lf]

No matter how you "batch" stuff together (or attempt to) it makes no difference.

You need to have:

Some way of identifying the start of a block of data,
A mechanism to receive the entire block a byte at a time, and
Some way of identifying the end of a block of data.

How you do that is entirely up to you.

Here's an example of how to arrange the storage:

class MouseRptParser : public MouseReportParser
{
    private:
        int dx[10];
        int dy[10];
        int dpos = 0;

    protected:
        void OnMouseMove (MOUSEINFO *mi) {
            dx[dpos] = mi->dX;
            dy[dpos] = mi->dY;
            dpos++;

            if (dpos == 10) {
                dpos = 0;
                for (int i = 0; i < 10; i++) {
                    Serial.print("X");
                    Serial.print(dx[i]);
                    Serial.print("Y");
                    Serial.print(dy[i]);
                }
                Serial.println();
            }
        }
};

What that gives you is a pair of 10-entry arrays, one for X and one for Y values. Each time a report arrives the current DX and DY values are stored. The pointer for where to store is incremented.  Then, if that pointer equals 10, reset it to 0 and print all the values.

I chose a format that gives you:

X3Y-2X2Y-4X6Y8X-3Y7X6Y38X176Y76X-4Y8X8Y3X39Y-32X71Y4

That is, an "X" followed by a decimal value for a change in X, and a Y followed by a decimal value for a change in Y. The whole lot is then terminated by a standard CR/LF line ending pair.


Problem with for loop I'm having trouble with the syntax of code. I want to have the motor turn when the next average the program measures is 100 or more greater than the previous average it measured. I don't know how to write the if statement:

if(average == (average>=100)) {
for(pos = 0; pos <= 120; pos += 1) {
  sServo.write(pos);
  delay(50);
}
for(pos = 120; pos >= 0; pos -= 1) {
  sServo.write(pos);
  delay(50);
}
}

The motor should

  turn when the next average the program measures is 100 or more greater than the previous average it measured

So simply write it:

// Old average is called "average"
// Compute the new average and put it in next_average
if ((next_average - average) >= 100)
{
  // Turn the motor
}
average = next_average;


Animated LED Strip & Sensing an Object Problem: Have an LED strip do some animation (say it takes 15 seconds for that line of code to run) meanwhile, have a sensor (tried methods: PIR sensor and ultrasonic sensor) watching to see if an object passes by.  If it senses an object, stop the light animation and make the lights do something else.

Issues: The PIR sensor takes too long to reset... I have the timing turned all the way to minimum and I am still able to count 12 seconds before it starts sensing motion again.  (Is there anyway to override this in the code?)  The other issue is the ultrasonic sensor, as far as I know, can't reliably run the first animation and watch for a change in distance then call an interrupt since an interrupt can only happen on FALLING, RISING, LOW, or CHANGE. This is an issue because the ultrasonic sensor is continuously sending LOW to HIGH then back to LOW for its pulses.

OVERALL QUESTION: How can I effectively sense if an object passes by a sensor, run new LED animation then back to where it left off without having to wait 12 seconds every time.  Is there some other hardware I could try? Please help!?

It seems as you are using the delay(); function for your code. The reason that it doesn't run anything is your Arduino does nothing during the function. The easiest option IMHO is using millis();. This will "return" a long datatype. Some example code (modified from example sketches in Arduino IDE):

/*
 created 2005
 by David A. Mellis
 modified 8 Feb 2010
 by Paul Stoffregen
 modified 5/16/14 by Anno. Penguin
 This example code is in the public domain.
*/

const int ledPin =  13;      // the number of the LED pin
int ledState = LOW;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated
long interval = 1000;           // interval at which to blink (milliseconds)

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

void loop()
{
  //Sensor code
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

Obviously, your code will be more complex than that. This one only blinks it, but you'll have to do some creative logic here. I don't know what the animation is, but most likely you'll need to add a few more variables (make sure to declare them outside loop() so they aren't disposed of each iteration!).


Arduino Nano - programmer is not responding I cannot seem to upload the simple blink program to my Arduino Nano. I keep getting the message:

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

What I have tried already with a lot of suggestions on Google. I have tried it on both a Windows 7 & 8 machine and with 2 different Nano's:

Set my Board to Arduino Nano
Set my Processor to ATmega168
Set my port to COM1
On windows 8 turned off driver signature
Installed the FTDI Driver
Checked my drivers in control panel

USB controllers says USB Serial Converter
USB Serial port says USB Serial Port (COM1)

Rebooted a Lot!

When I plugin the nano to the USB it starts blinking the L led 180 times a minute. When I start uploading, L blinks at about 80-100 times a minute, blinks the rx and then start blinking the L led fast again.

For me the problem was the selected "processor" type.

I had to change it to 328p (old bootloader).

Also, raise the IDE's verbosity, in order to have a nice progress bar when loading the sketch.

My specs:

OS: Linux Mint 18.3
Linux kernel: 4.13.0-37-generic
Arduino IDE: v1.8.5
board: the cheap and common Nano Chinese clone
USB to serial chip: CH340


Major difference between DTR signal and RTS signal? I actually had a doubt about what is the difference between the RTS signal and DTR signal ?
I already know this that the DTR signal is used to auto reset when we use Arduino and similar MCUs. Can anyone say what is the major difference between these signals and what is their active state ?

Electrically they are both the same. The difference is what they are used for.

DTR means Data Terminal Ready and indicates that the connected device is ready to receive data.

  Data Terminal Ready (DTR) is a control signal in RS-232 serial communications, transmitted from data terminal equipment (DTE), such as a computer, to data communications equipment (DCE), for example a modem, to indicate that the terminal is ready for communications and the modem may initiate a communications channel.

RTS means Request To Send and indicates to the connected device that it wants to send data.

  The DTE asserts RTS to indicate a desire to transmit to the DCE, and in response the DCE asserts CTS to grant permission, once synchronization with the DCE at the far end is achieved.

Basically DTR is used to indicate the presence of some equipment, and RTS is one half of hardware flow control (along with CTS) to start and stop communication.

On USB communication (e.g., using FT232 USB to UART adaptor, etc) the meaning is less clear. DTR is asserted when the port is opened (usually) and RTS is most likely not asserted at all. It's at the whim of the operating system and/or the driver whether DTR is automatically asserted or not, and whether RTS is even implemented.


Trouble with large numbers Probably something stupid, but I can't figure out how to work with these large numbers, then cast the result (which will be small) to an integer. I keep getting negative numbers, which I think means I'm overflowing somewhere.

int freq = 440;
int len = 256;
long timer = 2000000.0 / (freq * len);
int roundedTimer = int(timer);

I should get 18, but I'm getting -108...

freq * long, since they are both integers, are calculated as integers.

440*256=112640 - in binary that is 1 1011 1000 0000 0000 and trimmed to 16 bits becomes 1011 1000 0000 0000 which is -18432 and that is where the heart of your problem is.  Unless you explicitly say otherwise the Arduino's compiler does all calculations (except floating point) as 16-bit signed integers.

By casting the values to long it forces the compiler to 'overflow' the 16-bit limit and use a 32-bit limit instead:

long timer = 2000000 / ((long)freq * (long)len);

Another alternative is to define freq and len to be long from the outset instead of int.


How to troubleshoot the Arduino Mini and Arduino usb2serial? I am trying to get an Arduino Mini (R5, mega 328p) working.

Just connecting it to power has following effect: the on-board LED lights up. It's the power-on-led, I presume.

Since other Arduino devices often come with the blink-example pre-flashed I hooked up a LED to pin 13 - result: no blinking.

Curiously, connecting the LED to pin 12: blinking

Does the Mini come pre-flashed with a blink 'sketch' that blinks pin 12 instead of 13?

To test uploading I've connected it to an Arduino USB2Serial module. The module is labeled with 'made in Italy' and has printed 'USB2SERIAL LIGHT' on it where the LIGHT is overwritten with a blue marker.

I've connected it like described in the arduino mini guide.

In the IDE I've selected the board 'Arduino Mini' and the '328' CPU.

Unfortunately, uploading fails with:

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

The external reset is connected like in the guide. But I also tried to manually press the reset button (immediately before the upload, or long press and release after upload button is clicked). Still, the same error.

When the manual reset is pressed the pin-12-blinking stops for a while (perhaps the bootloader is then executed) but then starts again.

The Arduino2serial has 3 LEDs. The ON-LED lights up when connected to the USB. When hitting the upload button in the IDE, the RX-LED flashed shortly one time after a while. That's it.

Thus my question: How to I troubleshoot this? Can I test the arduino usb2serial on its own? What's up with the pin-12 blinking of the mini?

In case this matters, I am on Fedora Linux, uploading to other Arduino devices (Uno, Micro) works as expected.

update usb2serial: I just hooked up the Arduino usb2serial and connected the TX/RX pins via a jumper cable - a minicom session then results in text being displayed and the rapid flashing of the RX/TX LEDs. Disconnecting RX/TX again shows no display of any text inside minicom, and no flashing of the RX/TX LEDs.

I used following command line:

$ minicom -D /dev/ttyACM0 -b 115200

Thus, the usb2serial module seems to work.

update: I've checked all the jumper cables and there was a faulty one. With that replaced flashing works. After hitting the reset-button. The 'ext reset' pin is connected but the remote-reset does seem to work. Anyways, hitting the reset-button is easy-enough, for now.

final update: The root cause for remote-reset (a.k.a. auto reset) that the capacity of the used capacitor was too small. After exchanging it with a 100 nF one (as specified in the guide) the remote-reset works as expected. That means just hitting the upload button in the IDE automatically resets the device and the sketch is uploaded.

As always, it makes sense to check the parts in isolation, if possible.

Host system (Linux):

Tail the system log for errors
Check that ModemManager does not occupies the /dev/ttyACM0 device

USB2Serial:

Connect it via USB to the host without anything else connected -> the ON-LED should be on, the RX/TX LEDs should be off, the system log should display some udev progress messages (including vendor ids), the system should have a new serial device, e.g. /dev/ttyACM0
Open the serial port with a terminal (e.g. via minicom -D /dev/ttyACM0 [-b baudrate], disable local echo and type something -> nothing should be displayed
Connect the RX/TX pins to each other with a jumper cable -> typing in the terminal session should now result in rapid flashing of the TX/RX LEDs and the echoing of the text

Arduino Mini:

Connect just the minimum, e.g. just power from a 9V battery/5V power supply and the reset pin to +5 (with a 10KOhm resistor in series) -> the power-on led should turn on
The chance is high that the device comes with a pre-flashed blink examples that either uses pin 12 or 13 -> connect external LEDs to pin 12 and 13 (in series with 220 Ohm resistors) -> one LED blinks after power on
Hit the reset button on the mini -> any LED blinking should stop for a while and then continue

Arduino Mini with USB2Serial:

Make sure that both RX/TX pairs are crosslinked (like a nullmodem cable), i.e. RX <-> TX and TX <-> RX.
Follow the mini guide on arduino.cc or arduino.org it includes a picture of the cabling
Verify that the capacitor connected between the USB2Serial 'ext reset' pin and the Mini reset pin has a capacity of 100 nF, otherwise, the auto-reset might not work
In case the automatic reset does not work, press the on-board-reset-button just before the upload
In case the error persists, check for dodgy cables with a multi-meter

IDE:

Make sure that it works with 'easier' stuff, e.g. flashing to a Uno (the Uno is easier because the USB-2-Serial part is integrated)
Enable verbose logging during upload (in the preferences)
Update the IDE in case it is very old


Detailed analyse of memory usage When compiling a sketch, after linking, the build outputs a kind of forecast on RAM usage, e.g.:

  Minimum Memory Usage: 1456 bytes (71% of a 2048 byte maximum)

Is it possible to somehow get a breakdown or itemization of these 1456 bytes and details on exactly where in my code, or in included libraries, they are used?

Since you seem interested about RAM, rather than flash usage, I suggest
you look at the symbol table of your compiled program, which will be
more telling than the disassembly. On my Linux system, I usually do the
following:

avr-nm -Crtd --size-sort the_program.elf | grep -i ' [dbv] '

avr-nm is the utility for displaying the symbol table. It is normally
packaged with the Arduino IDE. It is invoked here with the following
options:

--size-sort is quite explicit
-C means “demangle the C++ names”
-r means “reverse sort”, i.e. sort from largest to smallest
-td means “display numbers in decimal rather than hexadecimal”

This will output the list of all symbols that have a size, in three
columns: size, type and name. You are only interested in the symbols
that consume RAM, i.e. those of type b (BSS, or uninitialized data),
d (initialized data) and v (vtable), either in upper or lower case.
The grep command is a standard Unix utility which is used here to
extract only the relevant lines from the output of avr-nm.

Example output for a small program:

00000068 B tx_buffer
00000068 B rx_buffer
00000034 B Serial
00000016 V vtable for HardwareSerial
00000004 B timer0_overflow_count
00000004 B timer0_millis
00000002 b loop::last_print
00000001 b timer0_fract

The first 4 entries come from the Serial object. The 3 entries
starting with timer0_ are used by the Arduino timekeeping functions
(millis(), micros() and delay()). The entry named
loop::last_print is a static local variable I declared in loop().


Is it possible to send data from internet server to ESP8266 behind proxy or regular requests from ESP8266 are required? It would be kind of push notification or something like that probably.
I can first connect to server and send it any data for "registration"...
I found many examples with websockets but all of them was about ESP8266 is like "server". That's not this case...

It seems evident that you don't want your ESP8266 running as a server of any kind. That's understandable given that server programs consume a fair amount of system resources (CPU, RAM, etc.) that are in short supply. That means you'll have to use your ESP8266 as a client and this means either

Polling - where the ESP8266 repeatedly connects to your "internet server" to explicitly ask for information at frequent intervals. Your internet server would have to be able to collect information in batches and hang onto it until your ESP8266 connects again to request the information.

Socket connections - where your ESP8266 maintains a consistent socket connection to your "internet server." Note that the HTTP protocol relies on socket connections, but clients open a socket connection, request a web page and its images, CSS, etc., then disconnects the socket. You can also use sockets at a more basic level as a bytestream. This programming can be tricky, but ESP8266 does have examples of TCP socket communication like WiFiClient and ethernet client.

Client approaches have a variety of headaches:

server has to hang on to information until the client comes back to retrieve it
you have to work up some kind of data structure to track which information has been handled and which work must still be done
latency issues -- i.e., what happens when there's a delay in processing information.

Server approaches also have challenges:

server programs can be tricky to write so that they keep running. a single exception or fatal error can crash the program
server programs are vulnerable to DDoS or other attacks, and can easily overwhelm a small device like ESP8266
firewall and networking issues -- depending on how this device connects to the internet, it may or may not have a consistent IP address where it can be found, the ISP that connects it may not allow incoming connections for the ports that it listens on, etc.


Arduino: incorrect calculation of long integer I'm doing a simple calculation with integers (on Arduino with ESP8266 12E), but I can't get the expected result and can't find the error. Can someone guide me?

#define A      200
#define B      A * 62
#define C      500

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

   unsigned long aux = 0;

   aux = (B * 500) / C;    // (12400 * 500) / 500 = 12400
   Serial.printf("aux = %d\n", aux);
   aux = aux * C;          // 12400 * 500 = 6200000
   Serial.printf("aux = %d\n", aux);

   // ERROR: Should result in "500", but is resulting in "1922000"
   aux = aux / B;          // 6200000 / 12400 = 500

   Serial.printf("aux = %d\n", aux); // It's printing "1922000"
}

In your #define of B you missed parenthesis (). Change your definition to:

#define B      (A * 62)

Without parenthesis you first divide 6200000 by 200 and then multiply result by 62, which is not what you intend.


where I can find ground? there is AVR AVR ATmega32 and a board within.
there is outputs for all ports (A, B, C, D) on board, and Vcc.
the problem is - I have no external GND output.
to watch current - I should search for GND pin everytime.
and now I need ground on my solderless board for LEDs and temperature sensor.

let's guess that I have no idea what is current or electricity.
so the question is: where I can find ground to connect it to solderless board?
maybe I can use something else, except MCU? (like my hand or smth :D)

I've just sorted things out.
There is two interfaces - ISP and JTAG. ISP is busy with programmer everytime, but JTAG is free.
So, I have found pinout of JTAG interface and achieved GND.
There is pinout:

(source: digital-circuitry.com)


Arduino Mega TIMER1 one second interval Is this timer set correctly for Arduino Mega? It should count exactly one second. And why when I print in serial monitor (seconds_passed++) is it incremented by 2 not by 1?

Full code on Pastebin: LINK

noInterrupts();
//set and initialize the TIMER1

TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0; // set entire TCCR1B register to 0
TCCR1B |= (1 << CS12);
TIMSK1 |= (1 << TOIE1);
TCNT1 = 3036;

attachInterrupt(digitalPinToInterrupt(ignition_pin), ignitionSignal, CHANGE);
interrupts();

ISR(TIMER1_OVF_vect) {
  //TIMER1 overflow interrupt -- occurs every 1sec --
  instantSpeed();
  LPG_Consumption();
  LPG_injector_open_duration = 0;
  unleadedConsumption();
  unleadinj_Open_Duration = 0;
  seconds_passed++;
  vss_pulses = 0;
  TCNT1 = 3036;
}

Your timer configuration is ok so far. Never the less I recommend using the TIMER1_COMPA_vect interrupt vector instead of TIMER1_OVF_vect which has the advantage of better readability (in my oppinion) and TCNT1 doesn't have to be reset in the ISR (instead, OCR1A is just initialized with 62500 once in setup()). Therefore, TIMER0 has to run in CTC (clear timer on compare match) mode and WGM12 has to be set in TCCR1B.

The reason why seconds_passed is incremented twice is because you Serial.print(seconds_passed++) in instantSpeed(). Printing on the serial interface is damn slow and using it in an ISR is a no-go!


Using an Arduino and multiplexer for writing to multiple outputs I'm attempting to use the multiplexer setup in this article with my Arduino Uno to control the output of LED's, as a way to fully understand the principles of multiplexing.

I'm working to modify the code in the article to switch from reading potentiometer values to writing voltage values to the LED's.

Below is the modified sketch; the biggest modified change is the loop in the writeMux function:

//Mux control pins
int s0 = 8;
int s1 = 9;
int s2 = 10;
int s3 = 11;

//Mux in "SIG" pin
int SIG_pin = 3;

//Voltage value to write to the LEDs
int testValue = 255;

void setup(){
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);
  pinMode(SIG_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
}

void loop(){
  for(int i = 0; i < 9 ; i ++){
    delay(1000);
    writeMux(i);
  }
}

int writeMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[10][4]={
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
//    {0,1,0,1}, //channel 10
//    {1,1,0,1}, //channel 11
//    {0,0,1,1}, //channel 12
//    {1,0,1,1}, //channel 13
//    {0,1,1,1}, //channel 14
//    {1,1,1,1}  //channel 15
  };

  //loop through the 4 sig
  for(int i = 0; i < 4; i ++){
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //read the value at the SIG pin
  analogWrite(testValue, SIG_pin);

  //return the value
  return 0;
}

Below is a photo of my circuit:

However, none of the LED's light up.

I'm fairly certain that this is more of a problem with the code rather than the circuit...any advice is appreciated!

According to the analogWrite() documentation, apparently the trouble are that you have swapped the args.

The syntax are analogWrite(pin, value), so, the piece

//read the value at the SIG pin
analogWrite(testValue, SIG_pin);

may work if you simply change to

//read the value at the SIG pin
analogWrite(SIG_pin, testValue);

That with respect to code, and i hope it helps you. At the other hand, the circuit, may be a bit dangerous (and can damage the Arduino or the mux) to use LEDs without a current limiter series resistor (330 - 1K Ohm would be nice values, 1/4 W). At least, by a light sight in a datasheet of the CD74HC4067, shows max currents of +/- 25 mA per pin. Similar currents can be driven by the Arduino (Atmega 328P).

So, all depends on the internal construction of the 4067, if are a transparent mux, maybe just with a single resistance in the SIG_pin in that range of resistances, would be fine.

Edit - Some Circuit Troubleshooting

There are some other little tests that you can do after that change in code:

Open the wire that goes from the Arduino to the common of the mux, then place at the output of the same Arduino pin, a LED-resistor series. Then change in program only the value of testvalue at the beginning of the code and check if the led changes their intensity according to that. That would be an Ok for that pin of the Arduino.
Reply the previous step to each of the channel pins. According to the code, you should see an increasing 1 Hz, 4 bits counter (rather, a BCD counter) in thet formed 4 led array. That would be an OK for the channel selection pins.
Remove the leds and connect back the opened lines.

Any fail in steps 1 or 2 may indicate that the pin are damaged but you can use another analog pin and other pins for the channels respectively. But if at step 3 it doesn't works, may be a damaged 4067 or a little hidden bad connection...


Default sketch working but arduino is not recognizing I have an arduino UNO and when I connected the device through the USB to the PC (with windows 7 64 bit),

The default blinking sketch, which comes shipped with it, is working,

but the device recognition sound is not playing.

and the device driver installation dialog never appeared and no arduino entry in the device manager.

And when I tried to upload a successfully compiled sketch from the ide 1.8.4 ,

It just says, 'problem uploading to board'
More verbosely, ' avrdude: can't open device""\.\COM1": the system cannot find the file specified'

The device is getting power and running the sketch,
But device is not recognized, maybe it is connected charge only, can I install the drivers manually?

Thanks in advance for any help.

Hahaha! I figured it out! The USB connector on the board's side was loose connected! It didn't felt like more pressable & when I pressed it enough, it firmly fitted.

When it loose connected, the board connects power only.

The drivers were installed automatically & it showed under COM6. I've got sketches running in no time.
I' ve tried a lot of knight rider patterns with a bunch of RGB LEDs then ;-)

Thank you @Majenko and the arduino stack exchage for your kind replies.


Arduino Uno not able to handle 2-dimensional array Now the code I'm writing in Arduino (Using Arduino) uses multiple 2-dimensional arrays. Now when I print some thing using the Serial Monitor it prints it correctly but when I declare and initialize the 2-dimentional array it won't print it.

Code:

void setup()
{
  Serial.begin(9600);
  int image_width = 56;
  int image_height = 96;

  int image_result[image_width][image_height];
  for (int i=0; i<image_height; i++) {
    for (int j=0; j<image_width; j++) {
      image_result[j][i] = 5;
    }
  }

  Serial.print("code works");
}

Now in this case "code works" does not print but when I remove the array declaration and initialization code works is printed. What is the problem?

Do 2 dimensional arrays work differently in Arduino or is it a space issue?

2D arrays work fine on arduino, but you run out of space very quickly.

An uno has 2 kilobytes of ram; your array has 56*96 = 5376 2-byte elements.

I would guess that you are writing over some critical memory value with a 5 at some point causing the program to fail.


Arduino Mega - Enabling CTC mode disables timer I'm trying to use timer3 on an Arduino Mega 2560 in CTC mode. However, enabling CTC disables the code entirely.

Here is the function I call in setup() to setup the times.

void SetupInterrerupt() {
  cli(); // Disable interrupts

  // Setup timer
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // Setup compare match register
  OCR3B =  CMP_FAST; // CMP_FAST = 40

  // turn on CTC mode:
  TCCR3B |= (1 << WGM32); // Commenting out this line makes the code work
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);

  sei(); // Enable interrupts

  Serial.println("Timers enabled");
}

And the interrupt vector.

// Timer 3 Interrupt
ISR(TIMER3_COMPB_vect){//timer1 interrupt 1Hz toggles pin 13 (LED)
  // do stuff...
}

As is, the interrupt doesn't execute at all. As noted in the code, commenting out "TCCR3B |= (1 << WGM32);" actually executes the interrupt, except the frequency is more like 1Hz instead of 720.

I'm using the arduino-lmic library, as well as some other data structure libraries. I don't think they use any timers, but since lmic is designed for Uno's, I figured that using timers 3 and up would be fine.

I'm a little rusty on my timers unfortunately. Is anyone able to spot my mistake?

Thanks.

I think your problem is that you are using the wrong "TOP" counter value register.

OCR3B =  CMP_FAST; // CMP_FAST = 40

should be:

OCR3A =  CMP_FAST; // CMP_FAST = 40

I am not too familiar with the workings of the AVR times, but according to the datasheet:

  In Clear Timer on Compare or CTC mode (WGM22:0 = 2), the OCR2A Register is used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter value (TCNT2) matches the OCR2A. The OCR2A defines the top value for the counter, hence also its resolution.

(Note: it only mentions the register for timer 2, but the same holds true for all the timers in the same class, including timer 3).

Since OCR3A is zero it never triggers a match.  And since there is only one counter (TCNT3) which gets reset to 0 on a match, there can only be one register to compare to, and that is the "A" register. The "B" register appears to be redundant in CTC mode.

You may also need to switch to the COMPA vector (I am not sure on this one TBH)


Best method of detecting peg in hole I’ve got a large wall with 1” holes scattered about. I’ve got some wooden pegs that fit perfectly into these holes. Now I’m thinking of creating a light installation based on the pegs, but i’m Struggling to find a way of detecting when a peg has been inserted into any hole.

What’s the best method of detecting them? I was thinking a stop switch that’s just placed on the edge of the hole to the peg activates it, but i’m Not sure how well that can be detected or if it would bend with use

We can't tell you the "best" method.  It depends on too many details we don't have.

Here are some options:

A reed switch at the bottom of the hole and a magnet on the peg.
A photo sensor at the back of the hole -- the peg blocks the light.
As you suggest, a switch at the side of hole.
Use contrasting colors on the wall and the pegs and detect the pegs using a camera and some sort of image processing (not an Arduino solution)

I think you are going to need to build some prototypes and experiment to find the best option for you.


Connecting a push button to a stepper motor problem I can't get this code to work. The button code and the step motor code works separately. However, when I code using an if statement saying when the button is pressed the motor will move or else it won't. PLEASE HELP.
const int buttonPin = 7;

int buttonState = 0;
int serialData = 0;

#define IN_1 8
#define IN_2 9
#define IN_3 10
#define IN_4 11
#define DELAY_TIME 30

int i = 0;

void setup() {
  Serial.begin(9600);
  pinMode(IN_1, OUTPUT);
  pinMode(IN_2, OUTPUT);
  pinMode(IN_3, OUTPUT);
  pinMode(IN_4, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.print ("start");
}

void loop() {
  buttonState = digitalRead (buttonPin);
  if (buttonState == HIGH) {
    //delay(1000);
    for (i=0; i<4; i++)
      Serial.println ("pressed");
    switch (i) {
      case 3: // ASCII value for '1'
        digitalWrite(IN_1, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_1, LOW);
        break;
      case 1: // ASCII value for '2'
        digitalWrite(IN_2, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_2, LOW);
        break;
      case 0: // ASCII value for '3'
        digitalWrite(IN_3, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_3, LOW);
        break;
      case 2: // ASCII value for '4'
        digitalWrite(IN_4, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_4, LOW);
        break;
      default:
        Serial.println("Not a valid case");
        break;
    }
    if (i == 4) {
      i = 0;
    } else {
      i = 5;
    }
  }
}

Your code makes no sense at all.  Let's break it down. First we'll reformat the code using the auto-formatter (AStyle) in UECIDE:

const int buttonPin = 7;

int buttonState = 0;
int serialData = 0;

#define IN_1 8
#define IN_2 9
#define IN_3 10
#define IN_4 11
#define DELAY_TIME 30
int i = 0;

void setup()

{
    Serial.begin(9600);
    pinMode(IN_1, OUTPUT);
    pinMode(IN_2, OUTPUT);
    pinMode(IN_3, OUTPUT);
    pinMode(IN_4, OUTPUT);
    pinMode(buttonPin, INPUT);
    Serial.print("start");
}

void loop()

{
    buttonState = digitalRead(buttonPin);

    if (buttonState == HIGH) {
//delay(1000);
        for (i = 0; i < 4; i++) {
            Serial.println("pressed");
        }

        switch (i) {
            case 3: // ASCII  value for '1'
                digitalWrite(IN_1, HIGH);
                delay(DELAY_TIME);
                digitalWrite(IN_1, LOW);
                break;

            case 1: // ASCII  value for '2'
                digitalWrite(IN_2, HIGH);
                delay(DELAY_TIME);
                digitalWrite(IN_2, LOW);
                break;

            case 0: // ASCII  value for '3'
                digitalWrite(IN_3, HIGH);
                delay(DELAY_TIME);
                digitalWrite(IN_3, LOW);
                break;

            case 2: // ASCII  value for '4'
                digitalWrite(IN_4, HIGH);
                delay(DELAY_TIME);
                digitalWrite(IN_4, LOW);
                break;

            default:
                Serial.println("Not a valid case");
                break;
        }

        if (i == 4) {
            i = 0;
        } else {
            i = 5;
        }
    }
}

Now that we have fixed the formatting we can see some very strange things:

if (buttonState == HIGH) {

First we're doing this for every loop iteration where the button is pressed. That means we're doing it over and over again until you release the button.

    for (i = 0; i < 4; i++) {
        Serial.println("pressed");
    }

Now we're printing the word "pressed" four times.  After this i will be set to 4.

The switch will now take an input value of 4, which is "Not a valid case". So nothing will happen.

Then:

    if (i == 4) {
        i = 0;
    } else {
        i = 5;
    }

i is always 4, so it will always set it to 0.  Quite what this block is supposed to achieve I have no clue. If it were supposed to be inside the for loop above then it would just kill the loop on the first iteration, since i, when 0, would not be 4, so would be changed to 5, which is > 4. It makes no sense and can achieve nothing of value.

As for the switch: if it were inside the for loop and able to get some varying values of i, it would just make each output briefly activate in turn. If that's what you need to drive your motor, then fine. However, it's never going to run since the rest of the program is just nonsense.


How do I see the command line equivalent of clicking Verify? I am using the ESP8266 board manager. I want to see how Arduino IDE compiles my code once I click Verify.

Why do I want to do this?

I am trying to integrate a C library for which there is now Arduino library package available. So I have to integrate it from source. I want to be able to specify custom -I, -L  and -l flags when I compile my code.

In the Arduino IDE switch on File>Preferences>Upload erbose and Compile Verbose

When you build you will see all the compiler commands

The verify is often a -v param in the command

You will find the esp8266 platform.txt in a location such as c:\users\[name]\appdata\local\arduino15\packages\esp8266...

The platform.txt contains all the compiler switches, the boards.txt in the same location can also contain board specific switches.

You can not specify different switches for different files in a compilation but you could compile your code into an archive then force it into the build process. Not sure if that is practical or not.


How to send an integer through pyserial with Python to an Arduino and get back the same result? There has been similar questions all over the internet but none of them seem to answer my question, so can anybody tell me what is wrong with this code and how I can fix it?

Python code:

import serial

arduino_linux=serial.Serial("/dev/ttyACM0",9600)
while True:
    print('write:',str.encode('90')) #print the sent value through the serial to check it with the readed value
    arduino_linux.write(str.encode('90'))#send the following value
    print('readed:',arduino_linux.read())#read the same value back from the arduino

my arduino code is as follows

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

}

void loop() {
  Serial.write(Serial.read());

}

this is a simple sample of a project, my aim from this code is to send the integer number 90 from the pyserial and make sure the value the Arduino is reading is the same integer.

In case if necessary my project is an object follower with object detector and after calculating all the angles and everything it sends them to the Arduino so the Arduino can act up on the servo's.

This is the result I am getting:

But I would like something like:

write:b '90'

readed:b '90', not b'9' or b'0'

I would also like to know how I can change these bytes to integers before I write them to a servo.

Use Serial.write() on Arduino to send raw bytes. print converts them to text.

read is not blocking, it doesn't wait for a byte and returns -1 if the receive buffer is empty. Check if read returned -1 or use Serial.available() to get the number of bytes in the RX buffer.

Serial 'echo':

void loop() {
  if (Serial.available()) {
    Serial.write(Serial.read());
  }
}


Issues with a basic circuit I am having some issues with a simple circuit. I would expect this circuit to light up this LED constantly when the Arduino is plugged in. I have the Blink tutorial sketch loaded, but I don't think that should matter with the pins I am using.

This is what I think I have going on: Arduino 5V Power --> BB power --> 100 Ohm resistor --> BB line 25 --> this LED --> BB line 30 --> BB Ground --> Arduino Ground

Please check out this picture for confirmation:

Thanks in advance for any help that you can provide!

Figured it out - stupid mistake as expected. The power and ground lines on my bread board don't go all the way across. They break right in the middle, as the lines show. I moved my ground connection to the left a few slots and it worked. Thanks for working through it with me jfpoilpret!


Automatic subtle colour changing on ws2812b with arduino I'm creating a wordclock and I'd like to change the ws2812b led strip color slowly, so that it fades from one colour to another. However, I'm new to arduino and I can't get it done and I also could not find anything on this anywhere (probably because of using the wrong keywords)

Currently I have a colour hardcoded like this:

void SwitchLED(int MyArray[], int n) {
     for (i = MyArray[0]; i < MyArray[0]+n; i++) {
          leds[i].setRGB((161,57,0);
     }
}

(The array in this code are the LEDs that will light up depending on the time I get from a ds3231).

So I would like a (random) starting colour to slowly change to another colour and so on. This in such a way that you will notice it only after a couple of minutes, so very slow and subtle.

I'm using the FastLED libary. I bit of help on this would be appreciated very much.

For the color, you can use the time (millis()) as a hue parameter.

void SwitchLED(int MyArray[], int n) {
    CRGB color = CHSV(millis()/1024, 255, 255);
    for (i = MyArray[0]; i < MyArray[0]+n; i++) {
        leds[i] = color;
    }
}

I used 1024 here to scale the time, so it takes 4 min 22 sec, to go through the hue cycle. And a power of two, should solve a visual glitch on millis() overflow.


Why does Adafruit guide for motors use transistors on ground rather than modulating the power source I'm going through the Adafruit Motors guide for Arduino, found here, and I'm struggling to understand how each of these parts play in. From what I understood, pulse width modulation is basically a way to send varying levels of power through a digital output source. Additionally, it seems that the guide is using a transistor with the PWM signal as the gate, so it can allow the percentage given by the PWM signal to control how much flow is given to the motor. However, what I'm confused here is that both the power and ground are interfacing with this transistor/diode setup.
This is more specifically what I mean, on the bottom seems really simple: the PWM signal comes on the yellow wire, fed through the resistor so that it doesn't fry the transistor into the gate.
After this though, there's a ground signal being passed into the source leg of the transistor, and the sink leg is connected to both a diode for power AND the ground of the motor? I might be misunderstanding how a diode works but this doesn't seem to make sense as to why the ground signal is being modulated.

My initial thought for this would be a system where only the power of the motor is varied by the PWM signal, sorta like in this way (apologies for the terrible drawing style, I haven't gotten used to some of the Arduino sketching software online):

I've not gotten to try this yet, but I assume it wouldn't work or would destroy components somehow since this does seem to be a simpler solution, and it's not being used. I was sorta trying to figure out 1) why my solution would be bad and 2) how the official solution works, as they haven't really given any actual schematic (not that I would understand it, haha) Any help would be appreciated! Thanks!

Your schematic
The blue line in your first schematic "going up" that you marked GND, is not really GND but one of the motor connections. If you look at the Adafruit schematic you can see this.
The motor in the Adafruit schematic in the link you provided is connected between 5V and the diode's Anode (and the transistor's collector).
Flyback diode
The diode is a so-called "flyback diode", connected between the motor connections to "soak up" back-EMF that occurs when the motor is turned off and its magnetic field collapses. If the diode would not be there, there would be a voltage spike on the transistor's collector, possibly damaging it.
Low-side switching
The "Adafruit" solution uses an NPN transistor as a switch on the low side of the motor when the I/O pin is high, like the schematic on the right. This is a very common setup as it has almost no disadvantages.
High-side switching
Your own suggestion (called high-side switching, shown on the right) would work as well (with the addition of a flyback diode) but it would need a different type of transistor, a PNP transistor. Also, the I/O inputs would work in an inverted way: when the I/O pin is low, the motor will be on and when the I/O pin is high, it will be off.
Note that high-side switching will only work when the supply voltage is lower or equal to the voltage that's on the I/O pins. You can't turn on a 12V motor this way, for example. With low side switching, you will not have this problem and you can switch higher voltages.

simulate this circuit – Schematic created using CircuitLab


arduino boot loader problem I am using atmega 328pu instead of atmega328p-pu. I am trying to upload the bootloader using AVR pocket programmer.

I have changed signature from 0x1e 0×95 0x0F to 0x1e 0×95 0×14.

(Relevant link)

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

(Note for the Arduino Uno: you'll need to add a 10 uF capacitor
  between reset and ground.)

From http://arduino.cc/en/Tutorial/ArduinoISP


It is possible to control brightness of an LED strip (connected using a relay and having a seperate power supply ) using output from an arduino? The circuit contains a relay interfacing with 12v power supply and LED strip. Can the brightness for this strip of LEDs be controlled using the analogWrite command?
This works perfectly for a single LED, but when i replace the LED with a relayed LED strip with its own adapter, it doesnt produce any perceivable output

As Gerben said relays are only for on/off control. If you need to fade led you should use transistor.

What kind of transistor?

It depends on power consumption (how many LEDs).

How to connect Arduino, LEDs, transistor?

This is schematics how to connect the strip. As i assume resistors are already on the strip.

And little bit simpler image :)


How can I update global variable within a loop from outside the loop? I have this code, but its not working. If I type "ReportFRQ 1" (or 0) it reports back that FrqON variable has changed but the behaviour of the loop doesnt. Basically I am trying to switch parts of the loop on and off using variables, which are updated by serial command.

The main body of the code was kindly provided by another answer as a way of commanding the arduino remotely with custom commands. I can get the arduino to do various things, but updating the behaviour of the loop by activating and deactivating different variables does not seem to work...

Any ideas? Thanks

#include <avr/pgmspace.h>
#include <FreqCounter.h>

#define BUF_LENGTH 128  /* Buffer for the incoming command. */

unsigned long int frq;
unsigned int frqON;

static bool do_echo = true;

/* Execute a complete command. */
static void exec(char *cmdline)
{
char *command = strsep(&cmdline, " ");

if (strcmp_P(command, PSTR("help")) == 0) {
    Serial.println(F(
        "echo <value>: set echo off (0) or on (1)\r\n"
        "freq: reports current frequency"
        ));
} else if (strcmp_P(command, PSTR("echo")) == 0) {
    do_echo = atoi(cmdline);
} else if (strcmp_P(command, PSTR("freq")) == 0) {
       FreqCounter::f_comp= 8 ;             // Set compensation to 12
       FreqCounter::start(10);            // Start counting with gatetime of 100ms
       while (FreqCounter::f_ready == 0)         // wait until counter ready
       frq=FreqCounter::f_freq;            // read result
       if (frq<1) Serial.println("OFF");
       if (frq>1) Serial.println(frq);
} else if (strcmp_P(command, PSTR("ReportFRQ")) == 0) {
       int frqON = atoi(strsep(&cmdline, " "));
       Serial.println(frqON);

} else {
    Serial.print(F("Error: Unknown command: "));
    Serial.println(command);
 }
 }

 void setup()
 {
Serial.begin(57600);
Serial.println("Frequency Counter");
}

void loop() {

/* Process incoming commands. */
while (Serial.available()) {
    static char buffer[BUF_LENGTH];
    static int length = 0;

    int data = Serial.read();
    if (do_echo) Serial.write(data);
    if ((data == '\b' || data == '\177') && length) {  // BS and DEL
        length--;
        if (data == '\177') Serial.write('\b');
        Serial.write(" \b");
    }
    else if (data == '\r') {
        if (do_echo) Serial.write('\n');    // output CRLF
        buffer[length] = '\0';
        if (length) exec(buffer);
        length = 0;
    }
    else if (length < BUF_LENGTH - 1)
        buffer[length++] = data;
 }

 if (frqON = 1) {
        frq=FreqCounter::f_freq;            // read result
       if (frq<1) Serial.println("OFF");
       if (frq>1) Serial.println(frq);
 }

    /* Whatever else needs to be done... */
 }

You have multiple problems here. First one:

You have a global variable:

unsigned int frqON;

However in your exec function you're creating a variable of the same name and writing to it. This doesn't change the global variable.

else if (strcmp_P(command, PSTR("ReportFRQ")) == 0) {
       //creates new local variable "frqOn" which overshadows global variable
       int frqON = atoi(strsep(&cmdline, " "));
       Serial.println(frqON);
}

To solve this and change the global variable, simply omit the int decleration.

Also your if check is wrong:

if (frqON = 1) {
        frq=FreqCounter::f_freq;            // read result
       if (frq<1) Serial.println("OFF");
       if (frq>1) Serial.println(frq);
 }

When you do if(frqOn = 1) you set the variable frqOn to 1. You however want to compare the values, i.e. use the comparison operator ==.


How to HTTP post a data to Node express API from a Arduino esp8226? I am HTTP posting a data to this web API https://morning-cliffs-85779.herokuapp.com/api/users from an Arduino connected to esp8226. I am using the wifiesp library to HTTP_POST data.

The REST APIs are hosted in Heroku.

When I post it the Arduino gives the response

  Connected to server
  [WiFiEsp] Data packet send error (2)
  [WiFiEsp] Failed to write to socket 3
  [WiFiEsp] Disconnecting  3

and the Heroku server gives the response

  at=error code=H13 desc="Connection closed without response"

Below is the Arduino code:

  if (client.connect(server, 80)) {
    Serial.println("Connected to server");
    // Make a HTTP request
    String content = "id=5bc58842bdfea0153bb27214&volt=7";
    client.println("POST /api/users HTTP/1.1");
    client.println("Host: morning-cliffs-85779.herokuapp.com:80");// ("Host": host:port)
    client.println("Accept: */*");
    client.println("Content-Length: " + content.length());
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.println();
    client.println(content);
  }

This is the Node Express API:

app.post('/api/users', function (req, res) {

console.log('here');

if (req.body.id) {
    DevReading.findByIdAndUpdate(req.body.id, {
        volt: req.body.volt
    }, function (err, reading) {
        if (err) throw err;

        res.send('Update Success');
    });
}

else {

var newDevReading = DevReading ({
    deviceName: 'test',
    volt: req.body.volt
});

newDevReading.save(function (err) {
    if (err) throw err;
    res.send('Reading Post Success');
});
}

});

Did it heres the code

`if (client.connectSSL(server, 443)) {
Serial.println("Connected to server");
// Make a HTTP request
String PostData = content + volt;
Serial.println(PostData);
client.println("POST /api/users HTTP/1.1");
client.println("Host: morning-cliffs-85779.herokuapp.com");
client.println("Cache-Control: no-cache");
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(PostData.length());
client.println();
client.println(PostData);
}`

Hope it helps some one


How do I connect my Luxorparts keypad to my Arduino? I just bought a 12 digit keypad from Luxorparts and it doesn't come with any schematics showing how it's wired at all. How do I figure out how to connect it to my Arduino?

There's a guide here that helped me out: Keypad Tutorial, that will show you the means of figuring out how the keypad is wired. I followed it and figured out that for that specific keypad (the Luxorparts keypad) the setup is as follows:

(From left to right on the keypad pins and on the rows and columns)

Pin1: Not connected
Pin2: Connected to the 2:nd collumn
Pin3: Connected to the 1:st row
Pin4: Connected to the 1:st collumn
Pin5: Connected to the 4:th row
Pin6: Connected to the 3:rd column
Pin7: Connected to the 3:rd row
Pin8: Connected to the 2:nd row
Pin9: Not connected

I modified the example code from the link above to reflect this specific Keypad:

#include <Keypad.h>

const byte ROW0 = 3;
const byte ROW1 = 8;
const byte ROW2 = 7;
const byte ROW3 = 5;

const byte COL0 = 4;
const byte COL1 = 2;
const byte COL2 = 6;

const byte ROWS = 4; // Four rows
const byte COLS = 3; // Three columns
// Define the Keymap
char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'#','0','*'}
};
// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte rowPins[ROWS] = { ROW0, ROW1, ROW2, ROW3 };
// Connect keypad COL0, COL1 and COL2 to these Arduino pins.
byte colPins[COLS] = { COL0, COL1, COL2 };

// Create the Keypad
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

#define ledpin 13

void setup()
{
  pinMode(ledpin,OUTPUT);
  digitalWrite(ledpin, HIGH);
  Serial.begin(9600);
}

void loop()
{
  char key = kpd.getKey();
  if(key)  // Check for a valid key.
  {
    switch (key)
    {
      case '*':
        digitalWrite(ledpin, LOW);
        break;
      case '#':
        digitalWrite(ledpin, HIGH);
        break;
      default:
        Serial.println(key);
    }
  }
}

To run that, simply connect each pin from the keypad, in order, to the arduino, so the second pin from the keypad goes to the second digital pin on the Arduino and so on.

I asked the question after I'd already figured out the answer in hopes of helping anyone else who bought that specific keypad.


What GUI software/platform can I use to control my Arduino MP3 player over the serial port? How would I make a GUI program on a different platform to control my Arduino MP3 player using the Arduino's serial port.

I would like the GUI program to show images like this for 'start':

...and this for 'next':

And when I click the images I want this GUI program to write strings to the Arduino's serial port. I want to do this because I have create an Arduino music player where a song can be selected by typing 'next', 'prev' and 'start' into the serial monitor.

Instead of using the serial monitor, I want to make a GUI program that has buttons that will send 'next' when I click the next button and 'start' when I click the start button.

When interfacing the Arduino with other software, consider using Jubito.


How to receive more than 64 bytes on Arduino? I am receiving about 90 bytes on the serial port. But Arduino has a serial buffer of 64 bytes only. Because of this limitation I am unable to receive further bytes.

char c;

void read_response() {
  while(Serial.available > 0) {
    c=Serial.read();
    Serial.print(c,HEX);
    Serial.print(",");
  }
}

I tried using the above function to read the serial data, but it is able to read only 64 bytes.

Another approach I tried as follows:

char rxdata[]={};

void read_response() {
  while(Serial.available > 0) {
    int len= Serial.readBytes(rxdata, 90)
  }
}

With this approach too, I was receiving only 64 bytes.

Serial.flush() also doesn't work as it waits for current transmission to finish. And I do not have control on transmission. The transmitter is sending 90 bytes continuously.

Please give me some suggestions.

But Arduino has a serial buffer of 64 bytes only. Because of this limitation I am unable to receive further bytes.

This assertion is nonsense. Certainly there is a buffer, but that lets you receive up to 64 bytes (put there by the serial interrupt service routine) before you retrieve a single one.

All you need to do is expeditiously retrieve the data (that is, do a Serial.read()) fast enough that you remove the data from the buffer and store it into memory.

You need to post a Minimal, Complete, and Verifiable Example (MCVE) that demonstrates your problem. For example, are you doing delay(1000) before attempting to read serial data?

See my post about receiving serial data without blocking and also Async (Serial) peripheral interface - for Arduino .


ESP8266 send TCP HEX packet with 4 chars I'm building a remote for my WiFi-RGB Lights. I have an ESP8266, which should send one TCP packet with 4 chars.

My code:

#include <ESP8266WiFi.h>

const char* ssid     = "Wifi";
const char* password = "wifikey";

void WiFiEvent(WiFiEvent_t event) {
  Serial.printf("[WiFi-event] event: %d\n", event);
}

void setup() {
  Serial.begin(115200);
  WiFi.disconnect(true);
  delay(1000);
  WiFi.onEvent(WiFiEvent);
  WiFi.begin(ssid, password);
}

void loop() {
  delay(1000);
  const uint16_t port = 5577;
  const char * host = "192.168.178.150";
  WiFiClient client;
  client.connect(host, port);
  client.print(char(0x71));
  client.print(char(0x24));
  client.print(char(0x0f));
  client.print(char(0xa4));
  client.flush();
  client.stop();
  delay(5000);
}

The problem: I send 4 TCP packets, while I should send 1 TCP packet with all 4 chars.

Thanks for your help.

After searching and experimenting on this, I believe the short answer to the question is that you need to send the command string like a buffer of characters AND put your Hex Coded command for the LED controller as an escaped string of characters.

Here is my code (it toggles the LED Controller between Green and Blue every 5 seconds, but you can extend this for other commands and colors as described at http://jpelectron.com/sample/Electronics/WiFi%20LED%20control/):

/*
Send Commands to LED Controller via Wifi Network and Wemos D1 Board
*/
#include <ESP8266WiFi.h>

const char* ssid     = "***yourWifiSSID***"; //Change this value for your network
const char* password = "***yourWifiPassword***"; //Change this value for your network
boolean connected = false;
boolean colorToggle = false;

void WiFiEvent(WiFiEvent_t event) {
    //Serial.printf("[WiFi-event] event: %d\n", event);

    switch(event) {
    case 3:
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(WiFi.localIP());
        connected = true;
        break;
    case 6:
        Serial.println("WiFi lost connection");
        connected = false;
        break;
    }

    // 0 : WL_IDLE_STATUS when Wi-Fi is in process of changing between statuses
    // 1 : WL_NO_SSID_AVAILin case configured SSID cannot be reached
    // 3 : WL_CONNECTED after successful connection is established
    // 4 : WL_CONNECT_FAILED if password is incorrect
    // 6 : WL_DISCONNECTED if module is not configured in station mode

}

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
    Serial.begin(115200);
    WiFi.disconnect(true);
    delay(1000);
    WiFi.onEvent(WiFiEvent);
    WiFi.begin(ssid, password);
    Serial.println("");

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

}

// the loop function runs over and over again forever
void loop() {
    //if we are connected
    if(connected){
      digitalWrite(LED_BUILTIN, LOW); //Turn on LED on the Board
      turnLEDSOn();
    }
    else
    {
      digitalWrite(LED_BUILTIN, HIGH); //Turn off LED on the Board
      setup();
    }
}

void turnLEDSOn() {
    const uint16_t port = 5577;
    const char * host = "192.168.10.2";  //Change to whatever your LED Controller IP is

     WiFiClient client;

     if (client.connect(host, port)) //Try to connect to TCP Server
     {
        Serial.println("Connected to LED Controller... ");
        if (colorToggle)
        { //Green
          char command[] = "\x31\x00\xff\x00\x00\x00\xf0\x0f\x2f";
          client.write((uint8_t *)command, sizeof(command));
          colorToggle = false;
          delay(5000);
        }
        else
        { //Blue
          char command[] = "\x31\x00\x00\xff\x00\x00\xf0\x0f\x2f";
          client.write((uint8_t *)command, sizeof(command));
          colorToggle = true;
          delay(5000);
        }

        Serial.println("Command sent ... "); // command is the color or animation sent to the LED controller
     }
     else
     {
        Serial.println("connection failed ... ");
     }

      if (client.available())
      {
        //Read from LED Controller
        char c = client.read();
        Serial.print(c);
      }

      if (!client.connected())
      {
        Serial.println();
        Serial.println("disconnecting ... ");
        client.stop();
        for(;;);
      }
}


How to shorten this code (because my sensor reads slowly)? I'm making a fare meter for our school project. I have too much lcd.print code. This code is not finished yet. My only concern is how to minimize the usage of lcd.print. I think it's the one that makes my sensor reading slow.
I'm new at Arduino; sorry if I have too many mistakes. I appreciate any of your answers. Thank you!
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <virtuabotixRTC.h>

virtuabotixRTC myRTC(6, 7, 8);
float d[4] = {};
int x = 0;
int f = 0;
int dis = 0;
const uint8_t disBut = 13;
int input = A0;
int state = 0;
int disF = 0;
int buttonstate = 0;
LiquidCrystal_I2C lcd(0x27, 20, 4);
LiquidCrystal_I2C lcd1(0x26, 20, 4);

void setup() {
  Serial.begin(9600);
  lcd.init();
  lcd.backlight();
  lcd1.init();
  lcd1.backlight();
  pinMode(disBut, INPUT);
  pinMode(buttonstate, OUTPUT);
}

void loop() {
  myRTC.setDS1302Time(18, 10, 10, 7, 18, 9, 2020);

  Serial.print("Current Date / Time: ");
  Serial.print(myRTC.dayofmonth);
  Serial.print("/");
  Serial.print(myRTC.month);
  Serial.print("/");
  Serial.print(myRTC.year);
  Serial.print("  ");
  Serial.print(myRTC.hours);
  Serial.print(":");
  Serial.print(myRTC.minutes);
  Serial.print(":");
  Serial.println(myRTC.seconds);
  delay(500);

  d[0] = (x * 1.73);
  d[1] = (x * 1.73);
  d[2] = (x * 1.73);
  d[3] = (x * 1.73);

  lcd.setCursor(8, 0);
  lcd.print(d[0]);
  lcd.setCursor(8, 1);
  lcd.print(d[1]);
  lcd.setCursor(8, 2);
  lcd.print(d[2]);
  lcd.setCursor(8, 3);
  lcd.print(d[3]);

  lcd.setCursor(0, 0);
  lcd.print(F("P1"));
  lcd.setCursor(0, 1);
  lcd.print(F("P1"));
  lcd.setCursor(0, 2);
  lcd.print(F("P1"));
  lcd.setCursor(0, 3);
  lcd.print(F("P1"));

  lcd.setCursor(6, 0);
  lcd.print(F("D="));
  lcd.setCursor(6, 1);
  lcd.print(F("D="));
  lcd.setCursor(6, 2);
  lcd.print(F("D="));
  lcd.setCursor(6, 3);
  lcd.print(F("D="));

  lcd1.setCursor(0, 0);
  lcd1.print(F("W="));
  lcd1.setCursor(0, 1);
  lcd1.print(F("W="));
  lcd1.setCursor(0, 2);
  lcd1.print(F("W="));
  lcd1.setCursor(0, 3);
  lcd1.print(F("W="));

  lcd1.setCursor(6, 0);
  lcd1.print(F("dscnt="));
  lcd1.setCursor(6, 1);
  lcd1.print(F("dscnt="));
  lcd1.setCursor(6, 2);
  lcd1.print(F("dscnt="));
  lcd1.setCursor(6, 3);
  lcd1.print(F("dscnt="));

  lcd1.setCursor(15, 0);
  lcd1.print(F("F="));
  lcd1.setCursor(15, 1);
  lcd1.print(F("F="));
  lcd1.setCursor(15, 2);
  lcd1.print(F("F="));
  lcd1.setCursor(15, 3);
  lcd1.print(F("F="));

  int counter=digitalRead(A0);
  if (state == 0) {
    switch (counter) {
      case 1:
        state = 1;
        lcd.setCursor(11, 0);
        x = x + 1; lcd.print(x);
        break;
      case 0:
        state = 0;
        break;
    }
  }

  if (counter == LOW)
    state = 0;
  if (state == 0) {
    switch (counter) {
      case 1:
        state = 1;
        x = x + 1;
        break;
      case 0:
        state = 0;
        break;
    }
  }

 if (counter == LOW)
   state = 0;
}

Your slowness is because on every single iteration of loop() you are updating the entirety of the display.  That's bad and wasteful.
You need to do two things:

Only display static information (the labels) once. Do that in setup().
Only display the variable data if it actually changes.

The first is simple: move any static text to setup(). That means things like lcd1.print(F("dscnt="));. It never changes, and the display doesn't "forget" it, so doesn't need constantly reminding.
The second is slightly harder. You need to keep two copies of the data. One that is the data at this moment, and one that is the data that is being displayed. Then you compare one with the other and for any items where they differ display them and update your saved copy.
So something like:
if (d[0] != d_saved[0]) {
    d_saved[0] = d[0];
    lcd.setCursor(8, 0);
    lcd.print(d[0]);
}

You can of course make that easier to program with a loop:
for (uint8_t i = 0; i < 4; i++) {
    if (d[i] != d_saved[i]) {
        d_saved[i] = d[i];
        lcd.setCursor(8, i);
        lcd.print(d[i]);
    }
}

Of course d_saved[4] needs creating in either the global scope or as a local static variable and initialising with some suitable "can never be" values (like -1 or something) so that the first time through it will always be different from the real values and display everything properly.


Bootup on lower power not functioning I have a custom Arduino ATMega328 board that generally runs at 5V @ 8MHz (using the Arduino Pro 3.3V 8MHz profile and bootloader). The main reason I'm using this setup is so that I can put the board to sleep when main power is disconnected and it starts being run off of battery power (3V from a coin cell). The 5V and 3V sources are diode OR'ed together and the 5V input is tied to INT0. In code, when it detects that INT0 has fallen low, it initializes sleep mode and everything powers down with the exception of the watchdog timer that keeps a 1Hz cycle to keep an internal count and check it the chip should be woken back up. This works beautifully when 5V power is applied first, then the battery is inserted, then 5V is disconnected. It goes to sleep and when 5V is brought back it wakes up and I can see it hasn't lost count.

However, the problem comes when 3V is applied first. I'm honestly not sure if it's even booting. But what it is supposed to do is boot, check if INT0 (Digital 2) is low and, if so, go right to sleep. By watching the current draw I see that it powers up to a few mA for a couple seconds, then drops to about 0.3mA (still higher than it should be in sleep mode). But when I re-apply 5V, nothing. The power draw goes back up but it is unresponsive (over FTDI serial).

Is there maybe something I'm missing that it can't be booted on 3V... in theory it should run just fine.

Update: I dropped an LED onto D13 and tried the blink sketch. Works fine when starting from 3V or 5V. However, when I run my firmware and start it from 3V, the LED just starts flashing wildly. I have no idea what's causing it since I never even setup D13 as anything in my code. But it makes me thing it's something to do with the bootloader...

So... turned out what was happening was all in code. Turns out that I was initializing an interrupt on INT0, when it was low, at the very beginning of my code. Problem was that when it started up on 3V backup power, INT0 was always low because INT0 is tied to the 5V line (it's how it knows to go to sleep). Because INT0 was low and the interrupt was triggering on low it was causing a constant interrupt to occur, never giving the rest of the program any time to run. Switched to enabling that interrupt only once I've entered full waking mode and it works fine now.


test for wrong wifi password? maybe this is a dumb question, but is there a way to test for wrong wifi password,

I know you can do WL_CONNECT to check if the password works, but is there a command for checking if the password is wrong? not just by waiting.

The information is available on SDK level. If you include #include "user_interface.h", you can use function wifi_station_get_connect_status(). It returns one of:

STATION_GOT_IP
STATION_NO_AP_FOUND
STATION_CONNECT_FAIL
STATION_WRONG_PASSWORD
STATION_IDLE

The WiFi.status() function uses function wifi_station_get_connect_status(),  but returns WL_CONNECT_FAILED for STATION_WRONG_PASSWORD.


Compile Error for Arduino Mega I am using the Arduino IDE 1.6.0,
There is a project that has compiled both for Due and Mega on another computer. But on my machine, it only compiles for Due. When compiling  for "Mega or Mega 2560", I get the following error:

  /Arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/bin/ld: skipping incompatible /Arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/lib/libc.a when searching for -lc
      /Arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/bin/ld: cannot find -lc
      collect2: error: ld returned 1 exit status
      Error compiling.

My newbie guess is something is wrong with AVR libraries. But how to solve it? Also could someone please explain what -lc is, which cannot be found? At first glance it looks like an option.

tldr; -lc means "link with the libc.a library"

The compiler takes your source code (*.c, *.ino) and produces "object" files ending in *.o.

The linker takes those compiled modules and links them all together to make the final executable, linking symbols in one file (such as variable references and function calls) with the definitions in the others (the actual variables and functions). But it also takes libraries - predefined collections of object files - and links those in as well, if necessary.

Libraries are files of the form lib*.a (a is for "archive"), and are distributed by software vendors as easy containers for their modules. The compiler/linker itself also uses them as the implementations for languages features such as printf() and digitalWrite(). The most fundamental library is libc.a - the library containing the standard C implementation.

When you want to get the linker to use a library, you give it the -l option, with the library name appended (not including the lib prefix and .a extension). In short, -lc means "link with the libc.a library".

But if your development machine has support for numerous processors, there will be a number of libc.a files on it - how does the linker know where to look? Another linker option is -L (note uppercase), which defines the directories to look in to find libraries. The linker will look through the directories in turn until it finds the referenced library.

If you attempt to link modules that have been compiled for different processors, you will get linker errors when it does a sanity check. The reason your fix worked is because it now uses the correct directories to find what it is looking for.


OpenOCD with FT2232H on Arduino Mega (ATmega2560) I want to do on-chip-debugging on an Arduino Mega.
According to its datasheet, the ATmega2560 chip supports JTAG. (IEEE 1149.1 compliant)

Can I use a generic FT2232H interface to do on-chip-debugging on this?

How would a OpenOCD config file look like for this purpose?

Thanks in advance!

The chip seems to support it:

  Multi-Protocol Synchronous Serial Engine (MPSSE) to simplify synchronous serial protocol (USB to JTAG, I2C, SPI or bit-bang) design.

You'll have to play with the drivers,
and check to see that Arduino brought all the JTAG pins out to header pins.


Analog thermistor readings are wrong There are some discrepancies between what is read by the analog channel for a thermistor, ohms values directly obtained on the thermistor using an ohmmeter, and another digital temperature sensor.

Figure 1: Left column (y axis) is degree Celcius; x axis is time (minutes). Orange is what was read by the analog channel (thermistor); in yellow the reading by a commercial digital sensor; and in green, manual readings of the thermistor using a ohm-meter.

A bit more context, we are building a simple system to read the temperature from a thermistor via an analog channel. Code algorithm is very similar to what is found here and the electronic layout inspired from here. When we ran into problems,  we just went back to the working basics as instructed by those two above-mentioned references.

Pad resistor is 7K Ohms @ +/-1%, measured resistance was 6690 ohms
Thermistor is 2252 Ohms @ 25 degree Celsius. Coefficients are as follow, coefficient were solved following a calibration in a thermal bath:

COEFF_A = 0.0014644
COEFF_B = 0.00023888
COEFF_C = 9.8996E-08

Specs from vendor are here (PDF) factory coefficient are about the same. I tried to calculate with either factory and in-house calibrated and there is a few thousandth of a degree of difference between the two - not enough yet to explain the current problem

While investigating I saw some sketch with the same resistance for pad resistor and thermistor, but have seen other differing thus assume this is not an issue.

To troubleshoot and isolate the origin of the discrepancies of the orange line VS other reading, we used

other thermistors (every single one behave similarly as the orange line in the figure 1)
other digital temperature sensors (every single one behave similarly as the yellow line in the figure 1)
we try to put 2 analog thermistors and 2 digital temperature sensors on the same arduino - analog were consistant between each other (discrepancies) and the digital one were behaving as expected (correctly)
we switched the pad resistor, no effect
other arduinos (did not changed anything, every single one was repeatedly demonstrating the same behaviour )
used the system in a temperature controlled room and the discrepancy was still present for the analog channel and absent for the digital sensor.

To be clear, green and yellow are what we think is the 'real' temperature; and the orange is the discrepancy. About 1 - 2 degree differences

We used the raw analog value read by the arduino as an input to manually feed and solve the Steinhart–Hart equation (like using IPYTHON and by hand) and output is the same as the orange line. Did the same with the thermistor obtained by the ohm-meter (Green dots on figure).

What should be investigated next to solve the discrepancy between what is read by the analogue channel connected to a thermistor and what the same thermistor provide to the ohm-meter?

Sketch follows

#define THERMISTORPIN_0 0               // analog pin 0 on the board
#define SERIESRESISTOR_0 6990             // balance/pad resistor value (ohm)
#define THERMISTORNOMINAL 2252          // resistance at 25 degrees C
#define ZEROABS -273.15                 // zero Kelvin (Celsius)

#define COEFF_A 1.4644E-03          // Coefficient A for Steinhart-Hart eq.
#define COEFF_B 2.3888E-04          // Coefficient B for Steinhart-Hart eq.
#define COEFF_C 9.8996E-08          // Coefficient C for Steinhart-Hart eq.

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

void loop()
{
    float temp1;
    temp1 = Thermistor(analogRead(THERMISTORPIN_0),SERIESRESISTOR_0);
    Serial.println(temp1);
}

float Thermistor(int RawADC, long padResistance) {
  long Resistance;
  float Temp;
  Resistance = padResistance / ((1023.0 / RawADC) - 1);
  Temp = log(Resistance);
  Temp = 1 / (COEFF_A + (COEFF_B * Temp) + (COEFF_C * pow(Temp,3)));
  Temp += ZEROABS;

  return Temp;
}

One possibility that has not been mentioned yet: the issue may be
the calibration of your ADC converter. Your code carries the implicit
assumption that the voltage you measure is

V = Vref × RawADC ÷ 1023

The correct formula is

V = Vref × (RawADC + offset) ÷ scale

where offset is ideally 0 and scale is ideally 1024 (and not 1023,
as you are assuming). Since you are looking at relatively small
discrepancies, the “ideal ADC” assumption may not be a good enough. I
have calibrated 3 Arduino ADCs and found offsets between 2.2 and
2.4, and scale factors between 1026.1 and 1026.3. Thus, if you have an
accuracy issue, I recommend you calibrate your own ADC.

As a side note, you could expect slightly better accuracy if the
thermistor and the resistor are closer in resistance. Right now you have
a factor 3, which is not that bad, but you could use a 2.2 kΩ
resistor, which is a very standard value.


What is the difference using library of SoftwareSerial.h and ESP8266WiFi.h? What is the library I should use to upload the sensor data (ultrasonic and Infrared sensor) to the localhost server.

Because I saw some of the online resources using ESP8266WiFi.h library for the ESP01 and some of resources use the softwareserial.h library. So, what is the difference between these two libraries?

The SoftwareSerial is used to communicate with the esp8266 from other MCU. The ESP8266WiFi library is for Arduino sketch running in esp8266.

The esp8266 can be used with firmware as 'network adapter' for your sketch running for example in Arduino Uno. MCU in Uno has only one hardware Serial which is used to communicate with the computer over USB (to upload and use Serial Monitor). To communicate with the esp8266 usually a second Serial interface is created with SoftwareSerial.

But esp8266 can be used as Arduino board with "esp8266 Arduino core". This 'core' contains Arduino libraries to access the WiFi functions of the esp8266 from a sketch running in esp8266.


Manually added boards doesn't work in 1.8.5…? I'm trying to manually add board definitions in a boards.txt file in hardware subfolder of my sketches folder as per instructions here for instance: https://www.arduino.cc/en/Tutorial/ArduinoISP

They however do NOT show up in my board selection.

My sketches location where hardware subfolder should be placed:

Board defs:

~/D/Arduino ❯❯❯ cat ~/Documents/Arduino/hardware/boards.txt
##############################################################

atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

atmega328bb.upload.protocol=arduino
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=57600

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05

atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328p
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

atmega328bb.bootloader.tool=arduino:avrdude
atmega328bb.upload.tool=arduino:avrdude

BUT nothing show here:

I have restarted Arduino IDE.

Newer versions of the IDE (after 1.5) have a different folder structure where there is additional subfolders for maintainer and architecture.

<Arduino sketch folder>/hardware/<custom name>/avr/boards.txt

https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification


Is it advisable to use Serial.write in an ISR when loop() routinely uses Serial.read? I do not know much electronics.
I have Nano v3 as I2C master, it reads 5-byte packets (of delimtted data) from PC's USB port, processes it and forwards it.
I now need to implement a way to signal PC if something went wrong down the line. I don't want to clutter I2C channel and its just a flag so I think interrupt is best for my purpose.
While writing the ISR function I am not sure if its advisable to write data using Serial, because loop might have read 2-3 bytes of the 5-byte message packet. And I don't know if it will overwrite data coming from PC or what...
What will happen if I Serial.write(0x1) (suddenly, in an ISR function) while loop() was reading data from same Serial?
I don't know how to test this myself.

Reading and writing of serial data are separate functions. When you .write() you just append the data to the TX buffer. When you .read() you just take the next character from the RX buffer.
All actual sending and receiving, and filling/emptying of the buffers is done inside the ISRs for the UART module.
That said, you really shouldn't use Serial inside an ISR. This is because the sending and receiving is done by an ISR, and if you are in your ISR then the sending can never happen until you leave your ISR.  For the odd occasional byte it's not really a problem, but if the TX buffer fills up Serial.write() will block until the TX ISR has sent some data - which won't happen since your ISR is blocking the TX ISR.
So it's best to avoid any Serial operations inside an ISR. Instead you would normally set flags and values in an ISR then check for those flags in loop() to report anything.


This website in Arduino lists language references like functions and structures. What makes structures there different from functions? https://www.arduino.cc/reference/en/
Language Reference
Arduino programming language can be divided in three main parts: functions, values (variables and constants), and structure.
functions
For controlling the Arduino board and performing computations.
variables
Arduino data types and constants.
structure
The elements of Arduino (C++) code.
I find it really confusing that they had to separate the structures but also call them functions in their descriptions. I kind of want to get a visualization or organization of the different language references present in Arduino, but this just confuses me. Are structures in the website also functions, and mainly syntax can be classified into functions and variables? Can someone present a organization of language references that doesn't involve terminologies being mixed up?

What the website names "Structures" are code building-blocks for the programs you write. The main part there are conditional (if-else) and loop instructions (for, while) as well as mathematical operators. You use these constructs within your functions to control program flow or compute results. Functions, on the other hand, are sub-programs you can call to have certain tasks done. They might be pre-defined (such as the ones described on the language reference page) or written by yourself.
Now there are two exceptions to this rule, and maybe that's what's a bit confusing in the documentation: The functions setup() and loop(). These are functions, but make up the structure of your program. They are the main building blocks of an Arduino sketch, and that's probably why they're mentioned under "Structures".


Programatic FOTA (Firmware-Over-The-Air) upgrades with Uno R3 I have been searching for a way to upgrade the sketch on my Arduino Uno wirelessly (preferable WiFi, but not a must). Does the Uno support such function?
If not - are there any other boards that might support it?

Also, to further extend on the problem - I wouldn't want to upload a new sketch through the Arduino IDE but rather do it programmatically (trying to integrate it with a version management system of my own).

There's two ways you can go about this - hardware and software.

To do it in software would mean writing a new bootloader that supported whatever wireless medium you chose.  The bootloader might end up quite large and thus restrict the size of sketch you are able to support.  It may also require advanced programming techniques in order to fit it into memory.  Not a task for a beginner.

Doing it in hardware is easier but more restrictive.  You need a wireless medium that can emulate a serial device including the ability to perform a reset of the Arduino.  There are bluetooth interfaces for the Arduino that can perform this kind of functionality, but I am not aware of anything WiFi or Ethernet that even remotely comes close.

There are Arduino boards available with this kind of bluetooth interface built in.

A possible third option is something in between - you have two Arduinos (or some other external MCU based system, like an ATTiny for instance), the "target" and the "programmer".  The "programmer" is what is connected to the wireless and accepts instructions and commands over the air.  It is then capable of putting the "target" into bootloader mode (reset it) and pass data through to its serial port for programming.  It does mean the "target" isn't directly connected to the wireless though, so it is up to the "programmer" to support whatever wireless functionality is needed and communicate properly with the "target" to get it to do everything it should.  There is no way to do FOTA to the "programmer" though, so you're back at square one if you want to reprogram that...


counting pulses from encoder on interrupt 0 pin every 50 ms I want to calculate the number of pulses coming from motor1 encoder pin2 (Int0) as input , and motor 2 encoder pin3 (Int1), I am working now for the first motor (just for the first motor ) so I set timer 2 to count 50 ms then throw flag in this moment I have to send the number of pulses to my screen, but not succeeded cause i see   on my screen zeros and ascii caracters but not the  number of pulses.:this my code .

 volatile int  pulses = 0;

 int flag=0;
 int setbit = 0;
 int encoder_in = 2;
 void count() {

       pulses++;
     }

  void setup()
   {

 Serial.begin(115200);
 pinMode(encoder_in, INPUT);
digitalWrite(2, HIGH); //Enable pullup

// initialize timer2
 noInterrupts();           // disable all interrupts

TCCR2A = 0x00;
 TCCR2B = 0x07;
TCNT2 = 0x64;
//EIMSK = 0x03;     // Enable external interrupt INT0
//EICRA = 0x0f;    // Trigger INT0 on falling edge

 TIMSK2 |= 0x01;  // enable timer compare interrupt
interrupts();             // enable all interrupts
attachInterrupt(0,count,RISING);

 }
  ISR(TIMER2_OVF_vect)
{
TCNT2 = 0x64;            // preload timer
 setbit=setbit+1;
  if(setbit==5)
  {
  flag=1;
 setbit=0;

   }
}

 //ISR(EXT_INT0_vect)
 //{ pulses++; }

 void loop()
{

 if (flag==1)
 {

   Serial.println(pulses);
    pulses=0;

  }
  }

Check the Baud Rate in Serial Monitor. If baud rate is not correct i.e. 9600 bps then it will show garbage.

Remove the Timer and Wire Libs

add this code in void setup()

attachInterrupt(0,void_counter,RISING);

the above is for the the external interrupt input.

and attach your sensor/incoming pulse wire on Pin 2 on arduino.

make a new function like this

void_counter(){
pulses++;
}


I want to create 10 levels with one button but this code shows only level 1? #include <Adafruit_NeoPixel.h>
const int PIN = 4;
const int NUMPIXELS = 10;
const int BUTTONPIN = 6;
int buttonState = 0;
int PINState = 0;
int level = 1;
int dt = 100;
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  pixels.begin();
  pinMode(BUTTONPIN, INPUT);
  Serial.begin(9600);
}

void loop(void) {
Serial.println(buttonState);
  buttonState = digitalRead(BUTTONPIN);
  if (digitalRead(BUTTONPIN) == HIGH) {
    if (buttonState == 0) {
      buttonState = 1;
    } else {
      buttonState = 0;
    }
  }

  if (buttonState == 1) {
    opdracht(level);
  }
  else {
    if (level >= 10) {
      level++;
    } else {
      level = 1;
    }
    pixels.clear();
  }
}

//level 1
//void opdracht1() {
//  pixels.setPixelColor(0, pixels.Color(150, 0, 0));
//  pixels.setPixelColor(5, pixels.Color(0, 0, 150));
//  pixels.show();
//}

void opdracht(int x) {
  if (x == 1) { //level 1
    pixels.setPixelColor(0, pixels.Color(150, 0, 0));
    pixels.setPixelColor(5, pixels.Color(0, 0, 150));
    pixels.show();
  }

  if (x == 2) { //level 2
pixels.setPixelColor(8, pixels.Color(150, 0, 0));
pixels.setPixelColor(6, pixels.Color(150, 0, 0));
pixels.setPixelColor(1, pixels.Color(0, 0, 150));
pixels.show();
  }

You forgot to ask a question. So I will assume the intended question is
“Why does this code always show level 1?” and I will try to answer that.
The variable level is defined here:
int level = 1;

Its initial value is 1. Then it is updated here:
if (level >= 10) {
  level++;
} else {
  level = 1;
}

The first time this section of code runs, level has its initial value,
namely 1. The condition in the if evaluates to false, then the
statement
level = 1;

is executed, which assigns the value 1 to level (which has no effect,
as that was already its value anyway).
The next time that section of code runs, level has still the vale 1,
and the effect is the same as the previous time.


RadioHead library nrf24 sending and receiving struct data problem I am using RadioHead library for the communication between nrf24l01.
I am sharing the snippet of my code below because the code is too huge.
The problem i am facing here is on the receiver side i am not be able see the data i am sending , it is showing squares and not the proper characters.
my output showing to me is :

name :?!

skill :

Sender Code :

struct DataHolder {
  String name;
  String skill;
};

DataHolder dh;

RH_NRF24 nrf24(10, 9);

//THIS METHOD I AM USING TO SEND DATA FROM SENDER NRF
void sendtonrf(){

 dh.name = "xyz";
 dh.skill = "classA";

 nrf24.send((uint8_t *)&dh, sizeof(dh));

}

receiver code:

struct DataHolder {
String name;
String skill;
};

 DataHolder dh;

 void loop{

 if (nrf24.available()) {

  uint8_t buf[RH_NRF24_MAX_MESSAGE_LEN];
  uint8_t len = sizeof(buf);

    if (nrf24.recv(buf, &len)) {

    String str1 = (((DataHolder*)buf))->name;
    String str2 = ((DataHolder*)buf)->skill;
    Serial.println("name :" + str1);
    Serial.println("skill :" + str2);

    }
 }
}

Your problem is that you are working with pointers.  You have a pointer to a block of memory with some text in it, then you take that pointer, get the address of the variable that stores it, convert it to a pointer to an 8-bit value, and send that.  Which of course won't work.

Instead you need to send the content of the memory the pointer points to:

nrf24.send((uint8_t *)strm, strlen(strm));

strm is already a pointer, you don't need to convert it to a pointer with & - that just confuses things and gives you a pointer to a pointer, which in this context is garbage.

A struct made up of String objects will not do what you think it does.  A String object does not contain the string itself. Instead it just allocates an external block of RAM (from the heap) using malloc() and holds a pointer to that memory. If you try transferring a struct which contains String objects all you will be sending is the data associated directly with those String objects, including the pointer to the string content, which is completely meaningless to the remote end.

Instead you will either have to send the strings separately along with their length and some identifier to say what the string is, or rebuild the string content into a fixed size buffer.

Personally I would use a fixed size buffer. In this method you change your struct so it contains two character arrays with a fixed size. For instance:

struct DataHolder {
    char name[10]; // Room for 9 characters + NULL
    char skill[10]; // Room for 9 characters + NULL
};

Then copy your string data into it:

struct DataHolder data;

strncpy(data.name, "Fred", 10); // Maximum 10 bytes
strncpy(data.skill, "ClassA", 10); // Again, max 10 bytes.

Now you can send the struct in its entirety:

nrf24.send((uint8_t *)&data, sizeof(struct DataHolder));

The data sent (and indeed the data held in the Arduino's RAM) will be:

Fred\0\?\?\?\?\?ClassA\0\?\?\?

Where \? represents any possible character (undefined, basically, and depends on how the variable was created - if it's global it'll be all 0, if it's on the stack then it will be whatever was in that block of memory beforehand) and \0 is the standard C end of string NULL character (ASCII 0).

For receiving it's exactly the same. Use the same struct, and go:

struct DataHolder data;

int len;
if (nrf24.recv((uint8_t *)&data, &len)) {
    // Do something with data.name and data.skill
}

Or you can use a buffer and a pointer, which may be safer since you have no chance of overrunning the buffer with a message coming in that is bigger than the data structure size:

struct DataHolder *data;
uint8_t buf[RH_NRF24_MAX_MESSAGE_LEN];

if (nrf24.recv(buf, &len)) {
    data = (struct DataHolder *)buf;
    // Do something with data->name and data->skill
}

Note the change from . to -> for the struct access since it's now a pointer.

Also note that you don't want your struct to be any bigger than your maximum packet size. To send anything bigger you will have to chunk the data up and send it in little bits.


reversing a micro motor by reversing two pins - one Source and one sink? can I use this configuration of two pins to run a micro motor ,so I be able to change the polarity of the current (by the code itself-one time out pin1-high out pin2 - low , while next time one low two high!) every time I would like ?(and by changing the polarity OF THE CURRENT to the motor it will revers it) !

Thank's !

**Required:**

Drive micro-motor directly from two processor pins.

 - Pin 1 high / Pin 2 low for one direction.
 - Pin 1 low / Pin 2 high for other direction.**

This is not a very good idea if it can be avoided but yes, you can operate a motor that way,  providing that the motor current is low enough to meet the pin current ratings. It would have to be a very small motor to achieve this.

Take careful note of the current versus voltage drive capabilities of the processor concerned. While a pin may be shown as being able to source or sing 5 or 10 or 20 mA, this is accompanied by a voltage rise for a sink and voltage drop for a source, so at higher currents lower voltages will be available.

A danger is that motor noise may affect the processor.
Placing a small capacitor across the motor will help, and driving the motor through a small resistor from each pin will also help keep noise away from the processor. But depending on the motor used this may not be enough.
The series resistors will drop some voltage and so are limited in maximum allowable size.
The parallel capacitor will slow the direction transition - the larger the capacitor the slower the change.

Using drivers or "buffers" which are higher current rated would allow a larger motor to be driven and would help isolate the processor from the motor noise.

Ask further if any idea here sounds useful.

Added: Had a discussion with Gerben (below).
I'd avoided mentioning "catch diodes" but this is an add on that can help.
From each pin add a small Schottky diode* from pin to Vcc and pin to ground so that all 4 diodes are reverse biased.
(ie Cathode goes to Vcc = line on diode on upper diodes.
Anode goes to ground on "lower" diodes. )
These diodes are usually non conducting. If motor operation or switching causes spikes that rise above Vcc or below ground these diodes will conduct (slightly) before  the internal protection diodes do. This is not ideal but can help.
As Gerben notes, when reversing the motor, driving BOTH pins to ground until the motor has stopped and then applying reversing polarity can help. Also driving both high will do the same. There are pros and cons with either method.

eg BAT54 surface mount,   BAT48 through hole, 1N581x  or similar.


Measuring time between two photoresistors and printing time on lcd I am working on a project that is supposed to record the time difference between two photoresistors that are 4in apart. The photoresistors are sensing the passing of water or other liquids on a chute/ramp.

The liquids range from water to milkshakes so the time difference shouldn't be more than 2 or 3 seconds at most (I would think). I'm okay with the accuracy being off by a a few tenths of a second.

I am using Photo cell (CdS photoresistor) for my project.

I have looked online and haven't seen a similar project. I want to be able to display the time difference on a lcd.

I have my lcd up and running but I'm not sure how to code the time difference. My photoresistors are connected to A0 and A1 and I am using digital pins 7-12 for the lcd. If anyone has any advice that would be very appreciated!

I'm sure I missed something so ask any clarifying questions

The most accurate approach is via In out capture on your timer.

Alternatively you can use an interrupt to start and stop the timer.

The worst approach is to poll

However, phtoresistors are slow and generally inconsistent. This can lead to errors in reading. S phototransistor or diode works better.

Edit: it is crazy to try to read the signal in analog. Instead design the circuitry so that it breaches the digital low or high thresholds so you can use digitalRead instead.

You can simply use millis or micros to time stamp the events and calculate the difference.

If you want more precise timing measurements, Google ticks implementation.

edit 2:

here is what I tried:

if (dtime_running==0) {             //event 1 has not arrived
    if (EVENT_ON(EVENT1_PIN)) {     //event 1 has arrived
        dtime = time_now();         //time stamp the event
        dtime_available = 0;        //data not yet available
        dtime_running = 1;          //time measurement running
    }
} else {                            //event 1 has arrived and now wait for event 2
    if (EVENT_ON(EVENT2_PIN)) {     //and event 2 has arrived
        dtime = time_now() - dtime; //calculate the timing difference
        dtime_available = 1;        //data now available
        dtime_running = 0;          //stop taking measurement
    }
}

On two pulses that are 500ms apart, here is the measurement:

Notice that in the box on the upper right, dtime has a value of 500, just as we expected.

the risk with this approach is that if the loop has other tasks, jitters to the measurement will show up. but for slow events, or long time measurements, it may not matter that much.