Using buttons with Arrays I am trying to write a simple program that will cycle through an array using push buttons. My current version of the program uses if statements and prints lines.

My goal is to have contact information for 4 people stored in an array. I can either have an array of strings per person or make different arrays of strings for the different type of information (ie names, phone numbers).

I would like one push button to cycle through the data in one direction and another push button to cycle through the data in the other direction. This is my code so far using the if statements. I modified the code from a traffic light tutorial hence you will see some of the variables named after colors.

//------------------------------- Declare variables
int ledPinOne = 2;
int ledPinTwo = 3;
int ledPinThree = 4;
int ledPinFour = 5;
int buttonPin = 6;
int state = 0;
char user_name_array[32];
char econ_one_name_array[32];
char econ_two_array[32];
char econ_three_name_array[32];

//------------------------------- Setup
void setup() {
  Serial.begin(9600);
  //------------------------------ Sets pins for I/O
  pinMode(ledPinOne, OUTPUT);
  pinMode(ledPinTwo, OUTPUT);
  pinMode(ledPinThree, OUTPUT);
  pinMode(ledPinFour, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.println("ID");
  Serial.println(user_name_array);
}

//------------------------------- Main Program
void loop() {
  if (digitalRead(buttonPin)) {
    if (state == 0) {
      Serial.println("Athlete");
      Serial.println("John Smith");
      Serial.println("No allergies, no medications");
      Serial.println("  ");
      setLights(HIGH, LOW, LOW, LOW);
      state = 1;
    } else if (state == 1) {
      Serial.println("Emergency Contact - Sister");
      Serial.println("Eliza Smith");
      Serial.println("Cell - 333.888.777");
      Serial.println("  ");
      setLights(LOW, HIGH, LOW, LOW);
      state = 2;

    } else if (state == 2) {
      Serial.println("Emergency Contact - Hermosita");
      Serial.println("Jackie Smith");
      Serial.println("Cell - 777.888.7777");
      Serial.println("  ");
      setLights(LOW, LOW, HIGH, LOW);
      state = 3;
    } else if (state == 3) {
      Serial.println("Emergency Contact - Father");
      Serial.println("Michael Smith");
      Serial.println("Cell - 888.777.777");
      Serial.println("  ");
      setLights(LOW, LOW, LOW, HIGH);
      state = 0;
    }
    delay(1000);
  }
}

void setLights(int red, int yellow, int green, int blue) {
  digitalWrite(ledPinOne, red);
  digitalWrite(ledPinTwo, yellow);
  digitalWrite(ledPinThree, green);
  digitalWrite(ledPinFour, blue);
}

I also have a 4-LED setup. When the button is pushed one of the LEDs turns on and then when the button is pushed again it turns off and turns the second one on and so forth.

Thank you in advance for any help.

EDIT:

This question was asked again in a more detailed way and has more answers here:

Using a button to cycle an array

Let's just deal with character strings.

The truth of the matter is that Arduino programming uses the language C.  C is very common and you can search for help in many places.

There are several ways to deal with strings in C.  In this example we are using an array of pointers to strings:

// let's make our own array of strings
char *states[] = {
    "California", "Oregon",
    "Washington", "Texas"
};
int num_states = 4;

for(i = 0; i < num_states; i++) {
    printf("state %d: %s\n", i, states[i]);
}

The output of this code looks like:

state 0: California
state 1: Oregon
state 2: Washington
state 3: Texas

I grabbed this example from here.

added later...

The method "printf" is normally not used in Arduino land.  So that "for" loop would look more like:

for(i = 0; i < num_states; i++)
{
 Serial.println("state ");
 Serial.println(i)
 Serial.println(states[i]);
}


esp32 crashes when trying to dereference a pointer value I have a websocket listener that is giving me a std::string of my message payload (I want the bytes) and I wrote a function that pulls each of the bytes out and puts them into 32 bit integer variables, adds that integer to an array of 32 bit integers, and passes back the pointer address:
uint32_t *get32BitInt(WebsocketsMessage message)
{
  std::string raw = message.rawData();
  uint32_t chunks[message.length() / 4];
  int chunkIndex = 0;
  for (int i = 0; i < message.length(); i += 4)
  {
    uint32_t chunk = 0;
    for (int j = 0; j < 4; j++)
    {
      chunk <<= 8;
      chunk |= raw.at(i + j);
    }
    chunks[chunkIndex] = chunk;
    chunkIndex++;
  }
  return chunks;
}

And I know that parsing and array building works because if I add a loop before I exit the overall function call it prints them out just fine.

And in the function that calls the parser I can print out the address of the pointer that was passed back.
But, as soon as I try to dereference anything my microcontroller crashes:

I know that I'm pretty green to pointers and I'm probably misunderstanding something, but I keep looking at docs and examples of passing arrays as pointers and it seems right.
Also, something worth noting is that it doesn't seem to be an issue with the actual number printing, because if I store the first number of the array into a variable and then try to print a line after the assignment the controller crashes after the assignment but before the next serial print:

Ah, one of my friends pointed out the issue. It's a scope snag:

chunks is allocated on the stack in get32BitInt By returning a pointer to chunks, you are pointing to memory that is deallocated. Think of it as pointing to a member variable of a class that has already been destroyed
when you try to dereference deallocated memory, bad things can happen. usually in debug the compiler makes sure you fail hard
the easiest way to test this is to allocate chunks outside of that function and pass it in as a reference

So yeah, I was allocating memory within the scope of a function and then blowing that memory contents away when that functions scope ended.
I refactored my code to move the array outside of the scope of the parsing function and passed the pointer in to the parsing function to get populated:
void get32BitInt(WebsocketsMessage message, uint32_t *chunks)
{
  Serial.println("--------------------------------");
  Serial.println("raw parse:");

  std::string raw = message.rawData();

  // uint32_t chunks[message.length() / 4];
  int chunkIndex = 0;

  for (int i = 0; i < message.length(); i += 4)
  {
    uint32_t chunk = 0;
    for (int j = 0; j < 4; j++)
    {
      chunk <<= 8;
      chunk |= raw.at(i + j);
    }
    chunks[chunkIndex] = chunk;
    chunkIndex++;
  }

  Serial.println("parsed chunks:");
  for (int i = 0; i < 11; i++)
  {
    Serial.print(chunks[i], HEX);
    Serial.print(" == ");
    Serial.println(chunks[i], BIN);
  }

  Serial.println("--------------------------------");
}

void addWebsocketListener()
{

  client.onMessage([&](WebsocketsMessage message) {

    uint32_t gameFrame[message.length() / 4]; // *try moving gameFrame out of scope
    get32BitInt(message, gameFrame);

    Serial.print("game frame address: ");
    Serial.println((int)&gameFrame);

    Serial.println("storing first 32 bit integer in a variable");
    uint32_t firstNumber = *gameFrame;

    Serial.print("game frame first value: ");
    Serial.println(firstNumber, HEX);

    Serial.println("printing frame:");
    for (int i = 0; i < 11; i++)
    {
      Serial.println(gameFrame[i], HEX);
    }
  });
}

And now my controller isn't crashing :D

And now I understand scope when dealing with pointers a bit better :)


Compute yaw from magnetometer and accelerometer I use an Arduino and a 9 DOF sensor (gyroscope, accelerometer and magnetometer) and I'm trying to use the pitch, roll and yaw that the sensor gives me to rotate an object in unity.

I managed to correctly compute pitch and roll (the z and x axis in unity) from the accelerometer but it seems that I can't get the Yaw right. By that I mean that when I rotate my sensor pitch or roll it rotates my yaw too, in a weird way.

Code in the arduino to get the heading

void getHeading(void)
{
  heading=180*atan2(Mxyz[0],Mxyz[1])/PI;
  if(heading <0) heading +=360;
}

void getTiltHeading(void)
{
  //float pitch = asin(-Axyz[0]);
  //float roll = asin(Axyz[1]/cos(pitch));
  float pitch = atan( Axyz[0] / sqrt( Axyz[1] * Axyz[1] + Axyz[2] * Axyz[2] ) );
  float roll = atan( Axyz[1] / sqrt(Axyz[0] * Axyz[0] + Axyz[2] * Axyz[2]));

  float xh = Mxyz[0] * cos(pitch) + Mxyz[2] * sin(pitch);
  float yh = Mxyz[0] * sin(roll) * sin(pitch) + Mxyz[1] * cos(roll) - Mxyz[2] * sin(roll) * cos(pitch);
  float zh = -Mxyz[0] * cos(roll) * sin(pitch) + Mxyz[1] * sin(roll) + Mxyz[2] * cos(roll) * cos(pitch);
  tiltheading = 180 * atan2(yh, xh)/PI;
  if(yh<0)    tiltheading +=360;
}

Pitch and roll

    float _Pitch  = (float)(180 / Math.PI * Math.Atan( m_ResultX / Math.Sqrt( m_ResultY * m_ResultY + m_ResultZ * m_ResultZ ) ) );
    float _Roll = (float)(180 / Math.PI * Math.Atan(m_ResultY / Math.Sqrt(m_ResultX * m_ResultX + m_ResultZ * m_ResultZ)));
    float _Yaw = (float)(m_TiltHeadingResult);

Don't hesitate to ask for details.

I don't know how all your sensor's axis are lined up, but it looks like you should level the magnetometer readings by rotating them by -pitch and -roll to get back to the global reference frame, instead of rotating the magnetometer readings by the positive angles.

However, The pitch and roll angles in the code are both relative the horizon, not a set of euler angles that define a rotation between two states; because of this, they do not compose to rotate the magnetometer back into the global xy frame like I assume the equations are trying to do. The code is also only using atan for pitch and roll instead of atan2, so their range is only 180 degrees.

You need to make sure the rotation matrix you multiply your magnetometer reading by is based on the same conventions as the equations you use to get pitch and roll from the accelerometer, and that it cancels the observed rotation.

To do this correctly, I recommend you read into euler angles. You might also try searching around for a good library that handles 9-DOF sensor fusion for you.


Is there a simple (permissive license) Leonardo driver for a USB-to-USART bridge to substitute an FTDI chip? I'm making an ESP32 development board and I'm thinking about putting an Arduino Leonardo chip between the USB port and the ESP32's USART pins to act as a USB/USART converter instead of the FTDI chip so that I can program the ESP32 through a USB serial port like any other Arduino board.

Is there a library/sketch licensed under a permissive license (MIT, BSD, Apache, etc.) which can make the Leonardo chip act as a HID Serial Port device which has a device name I want for easy identification in Device Manager and which requires no special driver installation in Windows and Linux once plugged into the computer?

Thank you for your time.

Why not write your own?

First off, you'll want to create your own custom board definition. To do that, find the boards.txt file in the AVR core of your installation. Then find the block of entries that starts leonardo. and copy the whole block. Change the leonardo to a name of your choosing.

Then change the .name entry to give your board a new name in the IDE.

Finally look for the (renamed) entries:

leonardo.build.vid=0x2341
leonardo.build.pid=0x8036
leonardo.build.usb_product="Arduino Leonardo"

Of course the leonardo will be whatever you changed them to.  You can now give your board a new VID and PID to uniquely identify them - and also change the usb_product to name your board.

You can also add a myboard.build.usb_manufacturer="..." entry to change the manufacturer from the default of Arduino.

Now you have a board definition that identifies your board as what you want it to be.  So now just write a sketch that passes through the serial between USB and UART, and also handles the DTR and RTS signals to be able to enter flash mode on the ESP32 (hint: use Serial.dtr() and Serial.rts() to check the status of those signals).


Where can I know voltage between GND(ground) and each port of UNO R3? Currently I'm new to arduino uno r3.
Where can I find each voltage between each port and GND(ground)?
Or can the voltage be changed?
I don't want to break my led bulbs since large difference of 2 potentials

5[V] is ideal EMF(electromotive force) of arduino UNO R3.
Since I stated "ideal" ,the actual EMF be slightly lower than 5[V].
In this instance , EMF can be assumed as voltage between GND and port of UNO R3 as ports are connected only by a wire.


what is the right way to parse JSON to Arduino? i am trying to Turn an LED from a hosted website, though Arduino using the CC3000 wifi shield. It is working as it should. but i have to questions about optimising my code :

1) the Part where i parse my JSON is kind of sloppy, what is the right way to Parse the code so i can turn the LED on and off when clicking on the website buttons ?

2) i need to keep the arduino connected to the website, so i can always control the LED. Do i need to close the connection at the end ? if so, how can i activate the connection only when clicking the button on the website to active the LED.

#include <ArduinoJson.h>

// Include Libraries
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>

// Define Pins
#define ADAFRUIT_CC3000_IRQ   3
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10

// Define Variables
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIVIDER);

#define WLAN_SSID       "MyWeb"
#define WLAN_PASS       ""
#define WLAN_SECURITY   WLAN_SEC_UNSEC // Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2

uint8_t dhcpTimeout;

#define host "mygarden.comli.com" // Your domain
uint32_t ip;
String path   = "/light.json";
int port = 80;

int pin = 9;

void setup(void)
{
  Serial.begin(115200);
  delay(10);

  pinMode(pin, OUTPUT);
  pinMode(pin, HIGH);

  // Connect to Wifi
  cc3000.begin();
  Serial.println(F("Initialising the CC3000"));
  if (!cc3000.begin())
  {
    Serial.println(F("Unable to initialise the CC3000! Check your wiring?"));
    while(1);
  }

  /* Delete any old connection data on the module */
  Serial.println(F("Deleting old connection profiles"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Failed!"));
    while(1);
  }

  // Connect to Network
  beginning:
  Serial.print(F("\nAttempting to connect to ")); Serial.println(WLAN_SSID);
  cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY);
  Serial.println(F("Connected"));

  //Wait for DHCP to complete
  Serial.println(F("Requesting DHCP"));
  while (!cc3000.checkDHCP()) {
    delay(500);
    Serial.print(F("."));
    dhcpTimeout ++;
    if (dhcpTimeout == 60) {
      Serial.println(F(""));
      Serial.println("DHCP Timeout! Attempting to reconnect.");
      dhcpTimeout = 0;
      goto beginning;
    }
  }
  Serial.println(F(""));
  Serial.println(F("DHCP complete"));

  //get website IP
  ip = 0;
  Serial.print(host); Serial.print(F(" -> "));
  while (ip == 0) {
    if (! cc3000.getHostByName(host, &ip)) {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
  }
  cc3000.printIPdotsRev(ip);
  Serial.println("");
}

void loop(void) {

  Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);

  client.print(String("GET ") + path + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: keep-alive\r\n\r\n");
  delay(500); // wait for server to respond

  Serial.println(F("----------"));
   while (client.connected()) {
    String response = "";
    bool begin = false;
      while (client.available() || !begin) {
      char c = client.read();
      if (c == '{') {
        begin = true;
      }
      if (begin) response += (c);
      if (c == '"}') {
        break;
      }
      delay(1);

      }
      int start = response.indexOf("light\":\"") + 12;
      int end = start + 3;
      String LED_Control = response.substring(start, end);

      if (LED_Control == "onn") {
        digitalWrite(pin, HIGH);
        Serial.println("LED ON");
      }
      else if (LED_Control == "off"){
        digitalWrite(pin, LOW);
        Serial.println("led OFF");
      }

   }

  delay(1000);
  Serial.println(F("\n\nClosing the connection"));
  client.close();
  cc3000.disconnect();

}

And this is my JSON output

{"light": "off"}

Assuming that String response will contain the json {"light": "off"} and your program is ready to use the ArduinoJson library (#include <ArduinoJson.h> on top), a simple solution could be:

Step1 - declare and initialize StaticJsonBuffer object.

StaticJsonBuffer<80> jsonBuffer;

Step2 - deserialize the json from response.

JsonObject& root = jsonBuffer.parseObject(response);

Step3 - if the deserialization doesn't succeed, warn and break,

if (!root.success())
{
  Serial.print("parseObject(");
  Serial.print(response);
  Serial.println(") failed");
  break;
}

Step4 - otherwise, use json object to get the LED_Control.

  Is the json will really contain {"light": "onn"} or is a typo ?

String LED_Control = root["light"];

if (LED_Control == "onn") {  // 'on' or 'onn' ??
    digitalWrite(pin, HIGH);
    Serial.println("LED ON");
}
else if (LED_Control == "off"){
    digitalWrite(pin, LOW);
    Serial.println("led OFF");
}


Attiny85 PB4 works for analog output but not PB3? I can get PB4 to work but not PB3 on my ATtinny85.  I'm just lighting up an led (with 150 ohm resistor) (using internal 16mhz)

void setup() {
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);

}
void loop() {
  analogWrite(3, 15);//does not work
  analogWrite(4, 15);//works
  delay(500);
  analogWrite(3, 0);//does not work
  analogWrite(4, 0);//works
  delay(500);
}

The hardware PWM is only suported on pins with output compare altenate function on it. The pinout in your question shows Attiny13 but the rest of your question is about Attiny85, which has different capabilities from Attiny13

As you can see, only pins with PWM capability are PB0, PB1 and PB4


Digital pins are no longer outputting enough to click a relay I've been working on a project for awhile now, and I ran into a problem a week ago I couldn't solve. I'm using an Arduino uno R3.
My project involves the use of 4 relays triggered by the digital pins. Write a HIGH value, relay clicks. Write a LOW value, relay unclicks. Rather simple.
One day, I come back to it to discover it can no longer click the relays. No changes were made to my code that worked previously. The relay light came on, but no click. Could it be that I sent HIGH to 4 at the same time? My theory is that I could've drawn too much power at the same time, weakening it in a way that causes it to not output as much as it did previously.
I tested a relay on a different board and it works perfectly fine.

Not knowing the reference of your relay, my answer is generic but should suit your needs.
Relays need 2 things in order to work properly: a sufficient voltage source, and one that can provide enough current.
The Arduino output pins provide 5V on 5V boards or 3.3V on 3.3V boards. BUT, most Arduino GPIO can provide only 20 mA of current. That might not be enough for your relay. The solution here is to use a transistor to drive the relay.
Also, relay coils are inductive loads that generate voltage spikes when current is turned off. That voltage can rise much higher than 5V and damage your Arduino pins and weaken or destroy them. The solution to this problem is to add a flyback diode.
This is what a typical circuit with relay driven by an Arduino looks like:

When the Arduino pin is LOW, the transistor is turned off and no current goes through the relay.
When the Arduino pin turned ON, the transistor turns on fully saturated and the relay coil is energized.
When the Arduino pin is turned LOW, the coil generates a negative voltage and current is allowed to go through the diode, dissipating energy in the relay coil. More information on flyback diodes: https://en.wikipedia.org/wiki/Flyback_diode


Arduino Yun USB host - reading usb MIDI data and passing forward to another device I am starting simple, but for some reason I cannot find any examples online and I stuck with my task.

I have a usb midi keyboard, Arduino Yun, and a synthesiser that can accept midi via usb. The problem is that the synth doesn't send a voltage through its usb and the keyboard has only one usb that is used to send midi data and it's powered via it at the same time.

My idea is to use my Yun's USB host (which sends voltage too) to power my midi keyboard and grab all incoming midi data from the keyboard, then simply pass it unchanged through to my synth.

Where do I start? Do I need some python code for it or everything can be done with sketch code? I've done few arduino projects but I am new to usb host functionality  . This is my first step, later I would like to also convert usb-midi to 5-din-midi (old school connection), but that's different story.

Can you guys help me and point into the right direction? Anyone done something similar on Yun? I've seen some examples done on different boards, but it's all overcomplicated, I need simple read/pass usb solution. Thanks!

You need the USB Audio kernel driver and the aconnect utility:

$ opkg update
$ opkg install kmod-usb-audio
$ opkg install alsa-utils-aconnect

Then just connect the ports:

$ aconnect -lio
client 0: 'System' [type=kernel]
    0 'Timer           '
    1 'Announce        '
client 14: 'Midi Through' [type=kernel]
    0 'Midi Through Port-0'
client 40: 'SC-8820' [type=kernel]
    0 'SC-8820 Part A  '
    1 'SC-8820 Part B  '
    2 'SC-8820 MIDI    '
client 44: 'My Little Keyboard' [type=kernel]
    0 'My Little Keyboard MIDI 1'
$ aconnect "My Little Keyboard" SC-8820
$

(This is plain Linux and does not need to run anything on the ATmega.)


How to detect V-SYNC on the SparkFun MicroView? Is there a way to detect the start of the OLED screen refresh cycle (V-SYNC) on the SparkFun MicroView? There is no code for this functionality in the Arduino library; in fact it looks like the Arduino library is only set up to send data over SPI to the display, and not receive any data/status back.

Do you know how to access the internal state of the OLED screen directly, by polling some kind of status bit over SPI?

The only datasheet I can find of this OLED screen does not have SPI command details.

Update: here's a movie taken with an iPhone on "slo-mo" video, showing a full screen (all pixels on). There is clearly a screen refresh going on, which interlaces with the video frame rate.

The scenario you describe is called the Tear Effect. On the SSD1306, which the device you are interested in is based around, a Frame Synchronisation pulse can be emitted on the FR pin.

However it would appear that the specific SSD in use by SparkFun does not provide this pin from the SSD1306 on the external FPC connector, so there is no way of getting it.  Probably owing to the small size of the display a reduced size connector without extra pins like FR was used.

So no, you can't combat the Tear Effect with that display.

There is nothing you can do over SPI, either. That is simply because SPI is just too slow for such things. You would use the FR pin because it's instantaneous.  With SPI you would have to make a request to read a register, then read that register's value back. In that time, coupled with the question of exactly when would the register say it was at the start of a frame, the information would be completely meaningless anyway.


How to add this old BASIC code snippet to work in Arduino C++ for FastLED? I've been trying to implement this old code that randomly transitions to RGB color into my Arduino board that uses FastLED.

Static Col1, Col2, Col3 As Integer
Static C1, C2, C3 As Integer
If (Col1 = 0 Or Col1 = 250) And (Col2 = 0 Or Col2 = 250) And (Col3 = 0 Or Col3 = 250) Then
  C1 = Int(Rnd * 3)
  C2 = Int(Rnd * 3)
  C3 = Int(Rnd * 3)
End If
If C1 = 1 And Col1 <> 0 Then Col1 = Col1 - 10
If C2 = 1 And Col2 <> 0 Then Col2 = Col2 - 10
If C3 = 1 And Col3 <> 0 Then Col3 = Col3 - 10
If C1 = 2 And Col1 <> 250 Then Col1 = Col1 + 10
If C2 = 2 And Col2 <> 250 Then Col2 = Col2 + 10
If C3 = 2 And Col3 <> 250 Then Col3 = Col3 + 10
leds[x] = RGB(Col1, Col2, Col3)

Here is my Arduino setup:

#include <FastLED.h>

#define LED_COUNT 60
#define LED_OUT       13
#define BUTTON_IN     10
#define ANALOG_INPUT  A9
#define EXTRA_PIN_A    7
#define EXTRA_PIN_B   11

struct CRGB leds[LED_COUNT];

void setup() {
  Serial.begin(57600);
  LEDS.addLeds<WS2812B, LED_OUT, GRB>(leds, LED_COUNT);
  LEDS.show();
}

void loop() {
  //where to implement
}

Fairly simple. Understand what the basic code is trying to do and recreate that functionality in c.

In this case, it is looking for a set of conditions to trigger the generation of three random numbers which are then combined into a code for the run array.


OTA Update Esp8266 without IDE I was wondering if its possible to program the esp8266 to receive firmware updates without the use of an IDE to program.

Use Case:
This device should be setup to the WiFi network scan an IP for a firmware update and update itself if needed.

Any help is greatly appreciated. Thank you

This: https://github.com/arendst/Sonoff-MQTT-OTA-Arduino is a Arduino based firmware with support for OTA. It's written for Sonoff, but that is just a ESP8266 with a relay attached, you can easily adapt it to any ESP8266.

It uses a 'hard coded' address of a web server where it downloads the firmware, and updates are triggered by MQTT messages, but all of that should not be too hard to change to something else.


number generator show wrong segments on 7 segment display I created a program to show a random number on a 7 segment display. It shows a random number in the serial monitor but always shows the same segments 'a c d and g'. anyone know hopw to fix this without changing the base of the coding its for and exercise so i need to have most of the code like I wrote it.

int num_array[11][7] = {
  { 1, 1, 1, 1, 1, 0, 1 }, // 0
  { 0, 1, 1, 0, 0, 0, 0 }, // 1
  { 1, 1, 0, 1, 1, 1, 0 }, // 2
  { 1, 1, 1, 1, 0, 1, 0 }, // 3
  { 0, 1, 1, 0, 0, 1, 1 }, // 4
  { 1, 0, 1, 1, 0, 1, 1 }, // 5
  { 1, 0, 1, 1, 1, 1, 1 }, // 6
  { 1, 1, 1, 0, 0, 0, 0 }, // 7
  { 1, 1, 1, 1, 1, 1, 1 }, // 8
  { 1, 1, 1, 0, 0, 1, 1 }, // 9
  { 0, 0, 0, 0, 0, 0, 0 }
};  //OFF

int buttonState = 0;
const int button = 12;
int randVal;
bool pressVal;
void num_Write(int);
void setup() {
  Serial.begin(9600);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(button, INPUT);
}

void loop() {
  buttonState = digitalRead(button);
  if (buttonState == LOW) {
    turnOff();
    pressVal = false;

  }
  else
  {
    if (pressVal == false)
    {
      int pin = 2;
      for (int i = 0; i < 7 ; i++)
      {
        digitalWrite(pin++, num_array[11][i]);
      }
      randVal = rand() % 10;
      pressVal = true;
    }
    Serial.println(randVal);
    if (randVal == 0)
    {
      void zero();

    }
    else if (randVal == 1)
    {
      void one();

    }
    else if (randVal == 2)
    {
      void two();

    }
    else if (randVal == 3)
    {
      void three();

    }
    else if (randVal == 4)
    {
      void four();

    }
    else if (randVal == 5)
    {
      void five();

    }
    else if (randVal == 6)
    {
      void six();

    }
    else if (randVal == 7)
    {
      void seven();

    }
    else if (randVal == 8)
    {
      void eight();

    }
    else
    {
      void nine();

    }
  }
}

void zero()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[0][j]);

  }
  delay(250);
}

void one()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[1][j]);

  }
  delay(250);
}

void two()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[2][j]);

  }
  delay(250);
}
void three()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[3][j]);
  }
  delay(250);
}
void four()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[4][j]);

  }
  delay(250);
}
void five()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[5][j]);

  }
  delay(250);
}
void six()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[6][j]);

  }
  delay(250);
}
void seven()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[7][j]);

  }
  delay(250);
}
void eight()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[8][j]);

  }
  delay(250);
}
void nine()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[9][j]);

  }
  delay(250);
}
void turnOff()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[10][j]);
  }
  delay(250);
}

Note, this is not an answer to your question, but I like to show some programming improvements, making your sketch  much shorter and easier to maintain.

Instead of having all functions one, two, etcetera, use a parameter to pass the number. So you get this: (I couldn't test it as I don't have an Arduino IDE at hand). Also you can use a for loop in the loop function to set the output pins.

int num_array[11][7] = {
  { 1, 1, 1, 1, 1, 0, 1 }, // 0
  { 0, 1, 1, 0, 0, 0, 0 }, // 1
  { 1, 1, 0, 1, 1, 1, 0 }, // 2
  { 1, 1, 1, 1, 0, 1, 0 }, // 3
  { 0, 1, 1, 0, 0, 1, 1 }, // 4
  { 1, 0, 1, 1, 0, 1, 1 }, // 5
  { 1, 0, 1, 1, 1, 1, 1 }, // 6
  { 1, 1, 1, 0, 0, 0, 0 }, // 7
  { 1, 1, 1, 1, 1, 1, 1 }, // 8
  { 1, 1, 1, 0, 0, 1, 1 }, // 9
  { 0, 0, 0, 0, 0, 0, 0 }
};  //OFF

int buttonState = 0;
const int button = 12;
int randVal;
bool pressVal;

void num_Write(int);
void digit(int value);

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

  for (int pin = 2; pin <= 8; pin++)
  {
    pinMode(pin, OUTPUT);
  }

  pinMode(button, INPUT);
}

void loop() {
  buttonState = digitalRead(button);
  if (buttonState == LOW) {
    turnOff();
    pressVal = false;

  }
  else
  {
    if (pressVal == false)
    {
      int pin = 2;
      for (int i = 0; i < 7 ; i++)
      {
        digitalWrite(pin++, num_array[11][i]);
      }
      randVal = rand() % 10;
      pressVal = true;
    }
    Serial.println(randVal);
    if ((randVal >= 0) && (randVal <= 9))
    {
      digit(randVal);
    }
  }
}

void digit(int value)
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[value][j]);
  }
  delay(250);
}

void turnOff()
{
  int pin = 2;
  for (int j = 0; j < 7; j++) {
    digitalWrite(pin++, num_array[10][j]);
  }
  delay(250);
}

You can also remove turnOff if you treat it like digit 10 but that is not so clear (or put the implementation of digit to another function and call it from digit and turnoff.

To solve your problem, print the values of each pin to the serial monitor. If they are correct, there is a problem in your circuit. If they are incorrect, there is a problem in your sketch. In the latter case, add more print statements until you found the exact problem.

Update

Fixed void forward declaration to function call (see comment of chrisl)

If the digit function is never called, it means:

((randVal >= 0) && (randVal <= 9)) is false, however, that is not possible since it is initialized to 0 and with the rand function it gets always values between 0 to 9.
pressVal is always TRUE.

So check the value of pressVal, also add (lots of) print statements, especiallya after each if and else so you know exactly the flow of your sketch. You will see it's very easy to find the error. If you pinpoint the problem to a digitalRead that is not the expected value, THAN there is high likely a problem with your circuit (a button that is never going to be LOW or HIGH). In that case, you probably forgot a pullup/pulldown resistor.


How to turn off or stop Access Point network in ESP8266? I've created a code for ESP8266 12E with Arduino IDE, in which it'll operate as "Station Mode" or "Access Point Mode" on Wifi, depending on the situation. Everything works fine except when device was configured as Access Point, even when I turn off device and then turn on again and force the Wifi initialization as "Station Mode", the Access Point network keeps active.

Example: Let's suppose that I turned on the ESP8266 and initialized the Wifi as Access Point, and named the wifi network as "MY_WIFI_TEST". Let's assume now that I turned off the ESP8266 and forced it to turn on as "Station Mode". The ESP8266 typically connects to my network (the network of my gateway router 192.168.1.1), but keeps the network "MY_WIFI_TEST" active (the prior network as access point). You can not connect to this network, but it remains active.

How can I turn off or stop Access Point network?

My test code:

#include <ESP8266WiFi.h>

bool access_point_init(){
    // Access Point Mode

   Serial.begin(115200);
   IPAddress ip(192,168,1,254);
   IPAddress gateway(192,168,1,1);
   IPAddress subnet(255,255,255,0);
   char* ssid     = "myssidname";
   char* password = "12345678";

   WiFi.softAPConfig(ip, gateway, subnet);
   bool ret = WiFi.softAP(ssid, password);

   return ret;
}

void wifi_station_init(){

    // Station Mode
    Serial.begin(115200);
   Serial.printf("\n");

   WiFi.begin(net_ssid, net_pwd_ssid);

   IPAddress ip(192,168,1,10);
   IPAddress gateway(192,168,1,1);
   IPAddress subnet(255,255,255,0);

    WiFi.config(ip, gateway, subnet);

   k = 0;
   while ((WiFi.status() != WL_CONNECTED) && (k < 80)){
      delay(250);
      Serial.print('.');
      k++;
   }

   Serial.printf("\n");
   Serial.printf("IP address: ");
   Serial.println(WiFi.localIP());
}

void setup()
{
    bool my_condition = false;
    //...
    // my_condition = myLoadFunction();
    //...

   if (my_condition) {
        access_point_init();
   } else {
      wifi_station_init();
   }
}

I've already solved, by using a function of the library Wifi, specific for the connections in "Access Point" mode:

WiFi.softAPdisconnect (true);

Reference:
softapdisconnect


Why do we need to amplify the signal of an electret? I do understand from my reading that I should amplify the signal from an electret to be able to read it with an Arduino. I'd love to know the science behind that, why should we amplify the signal to be able to get a correct reading ?

Arduino (or any chip that uses ADC for that matter) has a resolution. For example, arduino analog read divides 5V to 1024 levels. A.k.a 0V -> 0, 5V->1024. That gives you 4.8mV per level.

Now assume that you want to read the voltage fluctuation of a very low voltage power supply that fluctuates from 0 mV to ~8mV. What does the arduino read? You'll see either 0 or 1. So basically, you just can't successfully read that low voltage with your current setup.

Now, if you use an analog OPAMP and amplify that signal to 5V, (0mV->0V, 8mV->5V) then you can use all 1024 levels available to you, provided by arduino.

That's why you need to amplify the signal.


I can't find what I did wrong int lightPin = 13;
int buttonPin = 2

void setup() {
  pinMode(lightPin, OUTPUT); //red
  pinMode(buttonPin, INPUT);
}

void loop() {
  int buttonValue = digitalRead(buttonPin);

  if (buttonValue == HIGH) {
    digitalWrite(13, HIGH);
  }  //red

  digitalWrite(13, LOW);//red
}  //red

In this example your missing a semi-colin after int buttonPin = 2, and your if statement should probably look like this
if (buttonValue == HIGH){
  digitalWrite(lightpin, HIGH);
}//red

else{
  digitalWrite(lightpin, LOW);//red
}//red/*

Also if you go into the examples in the Arduino IDE, under "digital", this sketch is called button.


Why NVIC_EnableIRQ handler function only run once? I have a code that spit out random number when the ISR register is ready:
#define TRNG_KEY  0x524E47
uint8_t lut[10] = {0xF6, 0x12, 0xAE, 0xEC, 0xD8, 0x7C, 0x7E, 0xE0, 0xFE, 0xFC};
uint32_t msk = 0x1FE;

void setup()
{
  Serial.begin(9600);
  PIOC->PIO_PER = msk;
  PIOC->PIO_OER = msk;
  PIOC->PIO_OWDR = ~msk;

  PMC->PMC_PCER1 = PMC_PCER1_PID41;
  TRNG->TRNG_CR = TRNG_CR_ENABLE | TRNG_CR_KEY(TRNG_KEY);
  TRNG->TRNG_IER = 1 << 0;
}

void loop()
{
  if (TRNG->TRNG_ISR == 1) {
  PIOC->PIO_ODSR = lut[REG_TRNG_ODATA % 10];
  }
  delay(500);
}

The code above works. However, when I tried to switch to internal interrupt:
#define TRNG_KEY  0x524E47
uint8_t lut[10] = {0xF6, 0x12, 0xAE, 0xEC, 0xD8, 0x7C, 0x7E, 0xE0, 0xFE, 0xFC};
uint32_t msk = 0x1FE;

void setup()
{
  Serial.begin(9600);
  PIOC->PIO_PER = msk;
  PIOC->PIO_OER = msk;
  PIOC->PIO_OWDR = ~msk;

  PMC->PMC_PCER1 = PMC_PCER1_PID41;
  TRNG->TRNG_CR = TRNG_CR_ENABLE | TRNG_CR_KEY(TRNG_KEY);
  TRNG->TRNG_IER = 1 << 0;

  NVIC_EnableIRQ(TRNG_IRQn);
}

void loop()
{

}

void TRNG_Handler(void) {
  PIOC->PIO_ODSR = lut[REG_TRNG_ODATA % 10];
}

The code only spit out one random number and then freezes, indicating TRNG_Handler(void) was only executed once. I cannot figure out why.
Thanks in Advance !

Two things:

Never use delay() inside an ISR. On some systems it may work, but on most it will just block. It's bad practice to have your ISRs run for more time that absolutely needed anyway.
You need to read the status register for the TRNG to clear the interrupt flag. You're doing that in your first code sample with if (TRNG->TRNG_ISR == 1) {.


Bluetooth distorts analog read? I'm working to make a simple pedometer with Arduino, and after managing to find an algorithm that correctly finds the steps, I added a bluetooth extension (the overly popular and cheap JY-MCU) to check the steps via bluetooth.
I am facing a strange issue, though: when the bluetooth device is powered and waiting for a connection (red led blinking) the analog read function that reads data from the accelerometer goes crazy (thus the pedometer finds a step each second or so). When the bluetooth is powered down or connected to a device such as a mobile phone this doesn't happen.
Did anyone have this problem before? What could be the issue? My setup is easy, you can see it on the image.

I had other sensors as well but since the problem stays even when there are only those two connected I posted the bare minimum setup.
At first I thought I could use some kind of pull-ups to stabilise the signal, but I really have no idea on where to tie them and if they can really be helpful at all...
Any help is appreciated.

You can try decoupling the power for the bluetooth:

The resistor value should be tiny - 10Ω is a good value to use - don't go much higher than that.  The capacitor should be nice and big - I have shown 100µF, but bigger is better - whatever you have that's nice and big.  (Make sure you wire it the right way round - check which pin is marked as -)  You might also want to add a small capacitor (say 100nF) in parallel with the large one.


Does using multiple HX711 amplifiers change the supply voltage of an Arduino? I’m creating essentially a load cell using an Arduino Nano and an HX711 amplifier. However, I want to have two HX711 amplifiers running off the same Arduino. Will that change the supply voltage since I’m using two (ex. Does it change from 5V to 2.5V)? I need an accurate supply voltage for the Wheatstone bridge equations to determine strain from the strain gauge readings, but I’m unsure what adding another amplifier will do to the supply voltage.

Will that change the supply voltage

No. Components and circuits connected in parallel add together their current requirements, but the voltage stays the same.


NodeMCU capable of key injection? Short version: Is the NodeMCU capable of key injection in the same way that an Arduino Teensy can be programmed with Duckuino script to function as a HID?

Long version: Recently, my 7+ year old iMac suddenly stopped working and now I am unable to boot into the Mac which is a right pain. Even more of a pain is that due to the fact that the iMac has a wireless keyboard as opposed to a USB meaning that I am unable to boot into Single User mode, recovery mode, safe boot etc. This is a pain as I am currently stuck with an iMac in an unsuccessful boot loop. I understand that the best option would be to buy a USB keyboard and use this separately; however, it turns out that one of my friends has a spare NodeMCU and said he's willing to lend it to me as he is pretty sure that the Duckuino script will work on it meaning that I could use the NodeMCU as a sort of impromptu keyboard to hold down the shift key on boot, effectively removing the need for me to buy and wait for a new USB keyboard.

I had found this video here on YouTube which explains the process of turning an Arduino into a "USB Rubber Ducky" but there is no mention of this working with a NodeMCU. Assuming that I have the ESP8266 addon for the Arduino IDE and was able to put the Duckuino script onto the NodeMCU, would the NodeMCU function as intended with the Duckuino script or is the NodeMCU hardware such that this would be impossible?

Thank you for any assistance,

Kind regards,
John

P.s. This is what my NodeMCU looks like:

No, you can't use a NodeMCU for this.

To emulate a USB keyboard you have to have a device with a main MCU on it which is directly connected to USB. The ESP8266 on the NodeMCU is not a USB-capable MCU, and so it uses a USB to UART bridge chip to connect the ESP8266 to the USB of your computer.

You can't program that bridge chip, so you can't make it anything other than a serial port.

Common devices that are directly USB connected and can emulate a keyboard include:

Arduino Micro
Teensy 3.X
Fubarino Mini / SD
Arduino Leonardo
chipKIT Lenny

And there are many more.

For 8-bit Arduino boards you need to look at the MCU it uses. If it's an ATMega32U4 as the main MCU then you can program it to be a keyboard.

Addendum: There are ways of making non-USB boards work as a keyboard. For ATMega328P based Arduinos and similar that use an ATMega16U2 chip as the USB to UART bridge, that bridge chip can be reprogrammed to appear as a keyboard.  For other MCUs there may be software "bit-banged" USB implementations available (such as V-USB), though YMMV with those implementations, and they require building extra hardware to interface the chip to the USB port.


Teensy 2.0 MIDI: Number of notes in a chord limited to 6? I am using the Teensy 2.0 with USBMidi in a project that allows musicians to use retro computers as "instruments" (https://github.com/fredlcore/midijoy). So far, all these computers had no more than four voices, so the problem I am encoutering now has not arisen so far.

When I now want to play a chord with more than six notes simultaneously, only the first six notes are received and played. However, if I release two from, let's say, eight notes, the remaining two notes are subsequently being played if these keys are still kept pressed.

Here is a script reduced to the bare minimum, when you press eight keys on the MIDI device one after another, you'll see that it stops after the sixth key, and when you then subsequently keep all keys pressed and release one after the other, you'll see that the "remaining" keys/notes will be received then:

void setup() {
  Serial.begin(38400);
  usbMIDI.setHandleNoteOn(doNote);
  usbMIDI.setHandleNoteOff(doNoteOff);
}

void loop() {
  usbMIDI.read();
}

void doNote(byte channel, byte pitch, byte velocity) {
  Serial.println(channel);
  Serial.println(pitch);
}

void doNoteOff(byte channel, byte pitch, byte velocity) {
  Serial.println(channel);
  Serial.println(pitch);
}

You have to configure the Teensy as a MIDI device so that the USBMidi libraries will be found.

Is there a hardware limit in the Teensy 2.0 that will prevent it from processing more than six notes at a time? Or is this a constraint within the library?

@Majenko pointed me to the root cause of the problem: I was sending MIDI notes via Ableton's feature of using the computer's keyboard. It seems that the OS (or the keyboard) cannot send/receive more than six simultaneous keystrokes.


Help with function template syntax I am trying to understand the following code snippet from the Espressif OTABasic example for the ESP32 wireless/BT module (see this repository for the full code).

 ArduinoOTA
.onStart([]() {
  String type;
  if (ArduinoOTA.getCommand() == U_FLASH)
    type = "sketch";
  else // U_SPIFFS
    type = "filesystem";

  // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
  Serial.println("Start updating " + type);
})
.onEnd([]() {
  Serial.println("\nEnd");
})
.onProgress([](unsigned int progress, unsigned int total) {
  Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
})
.onError([](ota_error_t error) {
  Serial.printf("Error[%u]: ", error);
  if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
  else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
  else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
  else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
  else if (error == OTA_END_ERROR) Serial.println("End Failed");
});

The initial 'ArduinoOTA' looks kinda like an implied 'with ArduinoOTA' statement, but I can't find anything like that in the reference documents.  I know it has something to do with the way the function templates in 'ArduinoOTA.h', but it's beyond me to untangle the syntax.

May I buy a clue, please?

TIA,

Frank

Thanks to all for the clues; I'm an old-time c/c++ programmer, but must have slept through the 'lambda function' class ;-).

To help my somewhat calcified brain, is it functionally equivalent (if more clunky) to write the above snippet as shown below with the handler functions 'unchained'?

    ArduinoOTA.onStart
([]() //lambda function
    {
        String type;
        if (ArduinoOTA.getCommand() == U_FLASH)
            type = "sketch";
        else // U_SPIFFS
            type = "filesystem";

        // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
        Serial.println("Start updating " + type);
    }
);

ArduinoOTA.onEnd
([]() //lambda function
    {
        Serial.println("\nEnd");
    }
);

ArduinoOTA.onProgress
([](unsigned int progress, unsigned int total) //lambda func with arguments
    {
        Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
    }
);

ArduinoOTA.onError
([](ota_error_t error) //lambda func with arguments
    {
        Serial.printf("Error[%u]: ", error);
        if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
        else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
        else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
        else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
        else if (error == OTA_END_ERROR) Serial.println("End Failed");
    }
);

TIA,

Frank

This is called (by me, anyway) "method chaining".

It's nothing special, really.  ArduinoOTA is just an instance of the class ArduinoOTAClass.

Each method of that class does what it needs to do, then returns a reference to the object that the method is within.  Which means that you can then call a method on that returned reference ... and so on.

All the rest of it is "lambda" functions - that is, functions that are embedded within the parameters of the functions being called.

The basic result is something like:

A.foo().bar().baz();

Where A.foo() returns A. A.bar() returns A. A.baz() returns A.

You can do the same with:

A.foo();
A.bar();
A.baz();


Connect arduino pro mini 3.3v to 5v Is it safe to run an arduino pro mini 3.3v by 5v?
I mean directly connect 5v to vcc not raw pin.

Yes you can.

The only difference between the 3.3 V and 5 V Pro Mini is the crystal and the voltage regulator.


Timer Accuracy Always off by 1uS I am using the ATMega32u4 to generate a pulse at 1 kHz. I am using Timer 3, which is a 16-bit timer and using a prescaler of 1, so I have a 0.0625uS resolution. The good news is that this is working, I can control the frequency and pulse length of the square wave. The issue is that I noticed the pulse always seems to be 1uS off.

If I set a period of 1000uS, and a pulse of 500uS, the oscilloscope shows a period of 1001uS and a pulse of 501uS.

If I set a period of 100uS, and pulse of 10uS, the oscilloscope shows a period of 101uS, and a pulse of 11uS.

If the Timer had an error percentage, then both the period and pulse should be off by the same percentage, but there are always off by the same 1uS length. I assume I am doing something wrong, so I have posted my code below.

const int pin1 = 4;

void setup() {
  //Set pin to output
  pinMode(pin1, OUTPUT);

  // Reset Timer 3 Control Register to 0
  TCCR3A = 0;

  // Set prescaler to 1
  TCCR3B &= ~(1 << CS32); //0
  TCCR3B &= ~(1 << CS31); //0
  TCCR3B |= (1 << CS30);  //1

  //Reset Timer 3 and set compare value
  TCNT3 = 0;

  // Enable Timer 3 compare interrupt A and B
  TIMSK3 |= (1 << OCIE3B);
  TIMSK3 |= (1 << OCIE3A);

  //Enable global interrupts
  sei();

  //Set Refresh Rate
  OCR3A = 1000;
  OCR3B = 100 / 0.0625;
}

void loop() {
  delay(100);
}

ISR(TIMER3_COMPA_vect) {
  PORTD &= ~_BV(pin1); //LOW
  OCR3A = 160;
}

ISR(TIMER3_COMPB_vect) {
  TCNT3 = 0;
  PORTD |= _BV(pin1); //HIGH
}

The problem is here:

ISR(TIMER3_COMPB_vect) {
  TCNT3 = 0;
  ...

If you want to get anything that vaguely looks like accurate timings,
you should never reset the timer. The MCU needs time to process an
interrupt: it has to save the program counter to the stack, load the
address of the interrupt vector, execute it (it's typically a jump),
save all the registers it needs to the stack, and only then can it start
executing the code you wrote in the ISR. From your experiment, it looks
like all this process takes about 1 µs. But don't take this delay
for granted: from time to time the interrupt will fire while the MCU is
processing another interrupt, and this will increase the latency.

You have two options:

Update the compare registers in order to program the next interrupts
some time in the future. In this case, the COMPB ISR would do
OCR3A = OCR3B + 160; OCR3B += 1600;. Do not worry about the
overflows: they do the Right Thing.
Let the timer reset itself to zero: it will then do so without
loosing a single cycle. See the CTC and fast PWM modes of the timer.

For your specific use case, PWM seems like the obvious choice. Not only
will the timer handle the resetting itself, it can also generate the
output signal without requiring you to write any ISR. Beware that in
this case the period of the signal is whatever you load in corresponding
compare register plus one, and the duration of the pulse is another
compare register plus one.

As a side note:

  // Reset Timer 3 Control Register to 0
  TCCR3A = 0;

I would also reset TCCR3B. The Arduino core configures both registers
for it's own purposes, so it would be safer to clear them both.


Good Arduino motor drivers I need some motor drivers that can control a DC motor with 10-15 A and 25 V. I can't find any shield that can do the job. I need to control 4 motors with these.

Can you suggest some models that are good with this?

And one more question: if a driver can control a DC motor in 2 directions, can it control 2 DC motors in one direction each?

We don't really answer "shopping questions".
You could contact several suppliers like Adafruit, sparkfun or maybe even Digikey, Farnell etc (ebay?).

If you search for: "15A dual h-bridge" you will find some motor drivers which should work for you.

If a driver can control a dc motor in 2 directions can it control 2 dc motors in one direction each?

Where are you going to use them for?
If you're only going in one direction, you won't need a motor driver.

An MOSFET (per motor) is good enough if you only drive one direction.
If you want both motors to be able to turn each direction, a dual h-bridge will do.


How does the Arduino send more than 6 bytes via I2C I have been working with the wire library (I2C) to send data from one Arduino to another.  I read that the Arduino can only send 6 bytes per cycle, but I have been able to transfer much larger strings.  This code works without error:

  Wire.beginTransmission(4); // transmit to device #4

  for(int i = 0; i < 20; i ++){
    char rand = random(65, 100);
    Wire.write(rand);
  }

  Wire.endTransmission();    // stop transmitting

How is this possible?  It seams that 32 characters can be sent without trouble.

I read this here: http://arduino.cc/en/Tutorial/MasterReader

  Arduino 1, the Master, is programmed to request, and then read, 6 bytes of data sent from the uniquely addressed Slave Arduino.

Now that I look at this again (after reading the responses) I think that the limit was set in the code sample.

There is no reason to believe there is a 6 byte limit.

The Arduino Reference makes no mention of a 6 byte limit.

The Wire.cpp defines 'txBuffer[BUFFER_LENGTH];' where BUFFER_LENGTH = 32 (defined in Wire.h). The maximum is 32 bytes, just as you noticed.


Reading Arduino serial data in Octave on Mac I am trying to read serial port data generated by Arduino in Octave on Mac. I installed and loaded the instrument-control package for the same. I used this piece of code to check if the package was installed properly

if (exist("serial") == 3) disp("Serial: Supported") else disp("Serial: Unsupported") endif

I do get an output saying Serial: Supported.

I am following the tutorial here for step by step guidance.
I next use s=serial('portname') to create a serial port object. However, I am not sure what name to use instead of COM5 on Windows for Mac.

I checked and my Arduino is connected to cu.usbmodem1421 so I tried following 3 options a)cu.usbmodem1421 b) usbmodem1421 c)1421 but in each case I get an error saying "serial: Error opening the interface: No such file or directory".

Could anyone tell me what port name I can use or if there are any suggestions for the big picture problem as to how to read Arduino serial data in Octave (on Mac)? Thanks for the help in advance.

You most likely need the full canonical pathname for the port:

/dev/cu.usbmodem1421

On the Mac, as in Linux and other Unix derivatives, most devices, serial ports included, are special files in the /dev directory.


Sending large structs via nrf24l01 leads to cliping of some structs members I started with building of the wireless temp/hygro/other values probes. I use 2 arduinos, both with nf24l01+ wireless transceivers, library used is rf24.h (https://github.com/maniacbug/RF24). Basically ping/pong test works for me - so each arduino communicates properly via nrf24l01+.
I added dht22 temperature sensor and just for testing I started with sending structure:

typedef struct{
  int A; // just counter to see if receiving new data
  float B; // temperature
} data;

data payload;

I send it from Arduino1 like this:

radio.write( &payload, sizeof(payload) );

Other Arduino2 receives the payload:

radio.read( &payload, sizeof(payload) );

This works perfectly and I am able to print the counter value as well as the temperature value on the oled display o Arduino2. The problem is when I add float C to the struct for sending/receiving hygrometer values. Then Arduino2 does not receive/display any valid hygro value, but there is just value of 0.00.

I think I know where my problem is - nrf24.h has possibility to set payload size for nrf24l01+ - both Arduinos have to use the same payload size (default is 16, min is 8, max is 32). I use 8 - as this looks to be the most reliable value when using larger distances between Arduinos.
When I tried to set payload size to 32 on both Arduinos:

radio.setPayloadSize(32);

Then it works and I can receive and display counter, temp, hygro values.
So it looks the nrf24l01+ sends a payload of either 8 or 32 bytes and when sending struct with INT, FLOAT, FLOAT - 8 bytes is not sufficient and 32 bytes of payload is needed. But when I will use many other values, I can reach also limit of 32 bytes payload.

I do not have much skills in C programming and also I do not fully understand how data packets are being transferred between nrf24l01+ modules- maybe I just need to adapt my send/receive code to handle sending of the larger structures. Maybe somebody could give me a hint.

Your payload is too big. You will have to split it to smaller pieces.

NOTE: If you'd use a library like RF24Mesh then you'd not have to worry about it.


SIM800L LED is not blinking I am using a SIM800L Module with esp32. I am using a 3.7V 2800mAh lipo battery to power the sim800L but the LED is not blinking. I am lookng for answers in web but evryone seems to have a different problem than mine. In other case the sim800l is at least blinkng or blinked once.
I have tested the led with multimeter and it glows so hopefully the board is okay.
Is the power supplied by the battery is not sufficient? I followed this tutorial

I am sure about the sim card as it is a working sim card in INDIA (of IDEA) and works fine in my smart phone.

So I Finally sort out the problem. Both Battery and Module was completely fine. The problem was with the connecting wires. The connecting wires for some reason was not capable to hold the 2amp current. As a solution what I did was, cut the legs of some  quarter watt resistance and solder them to the wire exiting from the battery and fed them directly to the vcc and ground of the module. This way it works perfectly fine.
Even it seems a weird problem with no proper explanation but this solution works for me.
-----------Editing for a better explanation-------------
So my problem was with the connecting wires. For some reason the wires I primarily used could not deliver the the current from battery terminals to the module. May be those wires had a higher resistance for which the current flowing through those could not stay at 2 ampere magnitude and by the time it traveerses the wires and reached to the module, it was no longer at 2 ampere and might be lesser than a certain value which could not trigger the module and so the module did not work.
what I did was cut some legs of a few quatter watt resistance (the metal leads getting out from the carbon resistance from both sides:pic added) and sholder them to the battery terminals. Since I knew the metal legs of quatter watt resistances had a very less resistance from my course that trick worked and delivered 2amp current through them to the module.
I am trully sorry for not attaching picture as I have already submitted the project and currently have no way to replicate the situation.


Why does this code not respond promptly to changes in the LDR reading? So, I wrote some simple code like this :

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
  Serial.begin (9600);
}

void loop() {
  LDRValue = analogRead(LDRSensor);
  Serial.println(LDRValue);
  delay(50);
}

The line will print the value of LDR sensor simultaneously, but when I add this "if" condition inside the loop :

 if (LDRValue < 100) {
   colorWipe(strip.Color(255, 0, 0), 50);
   colorWipe(strip.Color(0, 255, 0), 50);
   colorWipe(strip.Color(0, 0, 255), 50);
   colorWipe(strip.Color(0, 0, 0, 255), 50);
   theaterChase(strip.Color(127, 127, 127), 50);
   theaterChase(strip.Color(127, 0, 0), 50);
   theaterChase(strip.Color(0, 0, 127), 50);
   rainbow(20);
   rainbowCycle(20);
   theaterChaseRainbow(50);
  }

the LDR  value only printed once..

Is it a wrong "if" condition code ? I know it's kinda lame, but please give me some starting point, doesn't need to be fancy just a small lead will do, thanks!

edit : complete library

I'm going to lever off gre_gor's comment on the question.

The code you are calling (for example, rainbow) has delays in it:

void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

So we can see straight away that calling rainbow(20); is going to take at least 20 x 256 ms (256 iterations of the loop with a 20 ms delay) plus more because of whatever else it does. That is over 5 seconds already!

Then you call rainbowCycle(20); and then theaterChaseRainbow(50); so you won't get back to the main loop for a while.

How to fix? Well, it isn't just a case of adding a line or two. One solution is to rewrite without delays, but instead have a state machine.

An alternative would be to test the sensor in each loop. Let's guess your objective is to stop the display if the LDR gives a higher reading. You could copy/paste the functions in question, but test the LDR inside them, eg.

void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256; j++) {

    int LDRValue = analogRead(LDRSensor);   // <--- add these 3 lines
    if (LDRValue >= 100)
       return;

    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

Suggested improvement to example

The code below uses a technique of supplying a "callback function" to the functions that do the pixel displays. I modified the Adafruit example to show the idea:

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif

#define PIN 6

typedef bool (*AbortFunction) ();

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, PIN, NEO_GRB + NEO_KHZ800);

// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
// and minimize distance between Arduino and first pixel.  Avoid connecting
// on a live circuit...if you must, connect GND first.

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
  #if defined (__AVR_ATtiny85__)
    if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  #endif
  // End of trinket special code

  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

// function prototypes
void colorWipe(uint32_t c, uint8_t wait, AbortFunction fAbort = NULL);
void rainbow(uint8_t wait, AbortFunction fAbort = NULL);
void rainbowCycle(uint8_t wait, AbortFunction fAbort = NULL);
void theaterChase(uint32_t c, uint8_t wait, AbortFunction fAbort = NULL);
void theaterChaseRainbow(uint8_t wait, AbortFunction fAbort = NULL);

const byte LDRSensor = 0;

bool checkLDR ()
  {
  int LDRValue = analogRead(LDRSensor);
  return LDRValue > 100;
  }

void loop() {
  // start with black
  colorWipe(strip.Color(0, 0, 0), 0); // Black

  // Some example procedures showing how to display to the pixels:
  colorWipe(strip.Color(255, 0, 0), 50, checkLDR); // Red
  colorWipe(strip.Color(0, 255, 0), 50, checkLDR); // Green
  colorWipe(strip.Color(0, 0, 255), 50, checkLDR); // Blue
//colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
  // Send a theater pixel chase in...
  theaterChase(strip.Color(127, 127, 127), 50, checkLDR); // White
  theaterChase(strip.Color(127, 0, 0), 50, checkLDR); // Red
  theaterChase(strip.Color(0, 0, 127), 50, checkLDR); // Blue

  rainbow(20, checkLDR);
  rainbowCycle(20, checkLDR);
  theaterChaseRainbow(50, checkLDR);
}

// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait, AbortFunction fAbort) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
    if (fAbort && fAbort ())
      return;
    strip.setPixelColor(i, c);
    strip.show();
    delay(wait);
  }
}

void rainbow(uint8_t wait, AbortFunction fAbort) {
  uint16_t i, j;

  for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      if (fAbort && fAbort ())
        return;
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

// Slightly different, this makes the rainbow equally distributed throughout
void rainbowCycle(uint8_t wait, AbortFunction fAbort) {
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    if (fAbort && fAbort ())
      return;
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

//Theatre-style crawling lights.AbortFunction fAbort
void theaterChase(uint32_t c, uint8_t wait, AbortFunction fAbort) {
  for (int j=0; j<10; j++) {  //do 10 cycles of chasing
    for (int q=0; q < 3; q++) {
      if (fAbort && fAbort ())
        return;
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow(uint8_t wait, AbortFunction fAbort) {
  for (int j=0; j < 256; j++) {     // cycle all 256 colors in the wheel
    for (int q=0; q < 3; q++) {
      if (fAbort && fAbort ())
        return;
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, Wheel( (i+j) % 255));    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

The important addition is to add another optional argument AbortFunction fAbort to each function call. The default is NULL, in which case the function behaves the same as before. However, if supplied, the function is called. If it returns true then the display function exits (thus avoiding the delays), like this:

if (fAbort && fAbort ())
  return;

The first test is "does the function exist?" and if so, the second test calls the function and checks to see if it returns true or false.

The modified example shows the scrolling patterns on the NeoPixels, provided A0 returns 100 or less. The function that does this is here:

bool checkLDR ()
  {
  int LDRValue = analogRead(LDRSensor);
  return LDRValue > 100;
  }

That function is passed as an argument to the other functions, eg.

rainbow(20, checkLDR);

I have a page about writing callback functions.


I think i worn out all of my Arduino Uno memory Hi my Arduino Uno stacked with a motor driver shield was working perfectly however I am using the same board for a while now and suddenly my board stopped working.
When I upload a code no matter what code is the LED's on the board respond however the code is not executed it does nothing , the board doesn t even beep anymore.
Is there a way to clean the memory or something?
Please help.

To check if you really cannot upload anymore (assuming it's not a software error), try the following sketch

https://www.arduino.cc/en/tutorial/blink

This will blink the BUILTIN led.

There is very low chance to wore out your memory, you can write lots of times to it (like 10,000 times guaranteed, in practice mostly more).

But there can be another hardware problem, but first check if this simple sketch works.

Also (based on jsotola's comment), remove shields/wires.

Especially wires/shields using RX/TX since these pins are (somehow) used for loading a sketch.


How can I define integer inputs to a function and get array as an output? I am trying to write a function that takes integer values as an input and gives an array as an output. I have tried the following code but it doesn't show the output result in the serial monitor:

int *phi (int cur,int vol,int t) {
  int z[4];
  z[0]=1;
  z[1]=cur;
  z[2]=vol;
  z[3]=t;
//z=cur+vol+t;
  return z;
}

void setup() {
  // put your setup code here, to run once:

}

void loop() {

int result;
result=phi(1,2,5);
Serial.begin(9600);
Serial.print(result);

}

Defining the array in phi() returns a pointer to unassigned memory - it is no longer reserved once phi() returns. The next function call or interrupt (which you have no control over) will likely clobber the data.

A better choice would be to define z in the caller (loop() in this case) as an uninitialized array and pass it to phi() to fill and return. This is the more usual case, as it:

avoids using globals,
permits multiple calls to the function without clobbering previously returned data (you would pass different arrays in this case), and
it avoids statically defined arrays that may not be needed after the caller returns, in a memory-starved environment (this may not be applicable if loop() is the caller).

In short, it gives the calling function the greatest flexibility, while committing the least amount of memory.


Arduino Pro Micro clone clock cycle issue I have several Arduino Pro Micro clones that are giving me an issue where they work immediately after being programmed while the USB cable is still connected, but as soon as I disconnect and reconnect the USB cable the program fails. I was able to break it down to the simplest form and found that the clock cycle is off by what I estimate to be almost a factor of 10.

For testing, the only command in the loop is Serial.println(millis());. Immediately after programming you can watch the milliseconds scroll by in the serial monitor at the expected rate. Unplug and plug the USB, reconnect the serial monitor and now the milliseconds scroll by at about 1 second interval.

The Arduino IDE version is 1.6.8 and have tested it from both a Mac and Ubuntu with the same results. Also tested on 4 different boards with the same results. I also tested the latest Arduino beta with no change. Next I'm going to download some older Arduino IDE versions.

Any suggestions?

The fix for this issue was to reload the bootloader.  I used the SparkFun Caterina bootloader.


Switching time of a multiple input switch I basically have two switches
Both switches will be pressed simultaneously in different order
I want to know which switch was pressed first

Use External Interrupts is the short answer.
Longer version:
You probably want to make a buzzer system like what in family feud game show.
I assume you are using Arduino UNO/MEGA and or having experience with programming.
1/ Use INT0 and INT1 for button 1 and button 2.
When an interrupt is raised, the mcu jumps to a specific address to run the interrupt service routine. INT0 and INT1 vectors are pointing to two distinctive addresses to run 2 different functions. For this, mcu takes the least amount of CPU clock to capture which button press first.
2/ Use PCINT vectors which is PinChange Interrupt. But personally I prefer to call it PortChange Interrupt.
There are 3 PinChange interrupt vectors PCINT0, PCINT1, PCINT2 to run 3 distinctive service routines. But this kind of interrupt doesn't know which pin is changed.
So inside the interrupt service routine, you have to check for that specific pin. You can do this the arduino way digitalRead(button1) or capture the whole port register, ie. PORTB, PORTC or PORTD.
In a nutshell, PORTB holds values of digital pin 8 to 13 while port D hold values of digital pin 0 to 7 and PORC for A0 to A7.
You can shave off some CPU clocks (3-10 clocks probably) by put 2 buttons different PCINT vectors. So that each button still triggers distinctive function.
In 3 cpu clocks (or around 180 ns) a lot of things may change and you may not get the correct result.
3/ Polling in main loop()
This is the worst way to do it. Nevertheless, it still gives good result.
if (digitalRead(button1)==LOW) {
// do something
}

if (digitalRead(button2)==LOW) {
// do something else
}


Reading data from potentiometer with MISO and MOSI on same pin I am working with the MCP4131 Digital Potentiometer and I am running into some trouble. The MISO and MOSI functionalities are multiplexed onto the same pin. Obviously, this means that I have to have Pin 13 and 12 hooked into the same pin on the chip.

I want to read send a READ command to the chip so that I can get the current value of the POT; however, when I send the lower byte in order to retrieve the value, I simply am getting back whatever I send because pins 13 and 12 are hooked into the same spot.

Is there any examples on how to work with a module such as the MCP4131 where the MISO and MOSI are on the same pin? Thank you!

You need to do a little conversion:

Connect the SDI/SDO line to MISO on the Arduino.
Connect a 1kΩ resistor between MISO and MOSI on the Arduino.

Then you first send the command byte(s) to the slave. You will receive these back, but you can just ignore them.

Then you receive the data. You do this by sending 0xFF for each byte. The 1kΩ resistor means the slave can override the 0xFF from the MOSI. The MOSI -> MISO resistor effectively becomes a pullup resistor and is, to all intents and purposes, ignored (it's just in parallel to the pullup resistor internal to the slave).


Arduino or Raspberry Pi for my project A brief description of what I'm doing here. I wanna make a pet project, basically a device (be it Arduino or raspberry pi) that I can connect to via bluetooth / wifi (both preferably), that will be connected to a stereo system and allow me to play music. I essentially want to make a wireless sound system in my house.

My question is, is raspberry pi more adequate for my needs? Or would arduino get the job done? I know that raspberry pis are essentially mini computers, so I feel that the raspberry pi would be too much, since all I really need to do is design a bluetooth / wifi interface and send the signal to the aux cable connected to the stereo.

Any help would be really useful here. I've never worked with either/or, and this is my first project with Arduino / Raspberry pi (hello world). Thanks in advance.

EDIT: In response to comments below, a greater idea of what I want to do:

I want to design an item that will appear on local wifi as a sound device. i.e. on an imac / macbook I'd be able to right click on the speaker icon in the upper right and select it there). From there, I'm hoping to stream audio to the device, and have it play to a stereo that the arduino / raspberry pi would be connected to. I'd love to make this universal (i.e. possible to connect via your android phone / a windows machine), but I can imagine that part being a lot more difficult. I'd also like to add bluetooth functionality at some point, but that'd be in the future. Hopefully this gives everybody more of an idea of what I'd like to achieve here! I appreciate all the help so far.

As mentioned in the comments, a Raspberry Pi would be superior here.

The standard AVR (not Due/Galileo/Yun) Arduino is superior to the Pi in only one area: IO. It has a 5V logic that's more compatible than the Pi's 3.3V (although you can use a logic level shifter). The Arduino also features more PWM pins and an ADC, along with interrupts. An Arduino also is a lot simpler to use for basic projects, but it becomes impractical when you need more computing power.

A Pi excels at the data-crunching side of things. It can handle a lot more data than the Arduino could ever dream of, and then some! Just to put things in perspective, the Pi has a clock speed of 700 MHz by default and the Arduino Uno has one of 16 MHz (with a less powerful architecture).

For your purpose, the Pi's audio jack and ethernet port are unmatched on the Arduino. Sure, you can get shields that replicate these behaviors, but the Pi's built in functionality doesn't cost extra and it's more powerful.


Sensor for very low temperature (liquid nitrogen) I'm looking for a way to measure temperatures in range of 40 to -200 °C (100 to −320 °F). The usual solution DS18B20 works only down to -55 °C (-67 °F).

Any ideas?

p.s.
Precision of 2 °C would be good enough.

You probably want a K-type thermocouple (the most common type).

They have a range of around -200°C to +1350°C (depending on probe).

Alternatively a Resistive Temperature Device (RTD) can be used, since these have a typical range of around -240°C to 650°C with higher accuracy.

This might be of help to you: http://digital.ni.com/public.nsf/allkb/C50FA55B3B2F85D9862572D00083350E


I am getting blocks on my lcd screen 16*2 When I have tried interfacing my 16*2 LCD with Arduino I am getting only the black coloured boxes on my screen. What might be the problem?

Is there any solution to that? Do I need to connect any additional physical device to avoid that situation?

product is here lcd display 16*2

There are two possible problems, and you haven't stated which it is.

A single row of blocks (just the top row)

This is caused by either bad communication (wrong wiring) or incorrect code. Basically, the display isn't being initialized properly by your code for whatever reason.

Two rows of blocks (the entire display full of blocks)

The display is being initialized properly, so both your code and wiring are correct.  However, the contrast setting of the display is wrong. You need to check the wiring for your contrast potentiometer and adjust as necessary.


Why all blink tutorials use 330 ohm resistor When I do the led calculation I found 150 ohm resistor is enough for 3mm red led. If so why all arduino tutorials, like this one, are suggesting 330 ohm resistor?

I assume V = 5 Volt, diode forward voltage = 2V and diode forward current 20mA

150 Ohms may be "enough", but it's often still far too bright, so many tutorials keep a lower limit of around 10mA to help the LED live longer without affecting the application.

You'll probably find that red LEDs are still visible at 1mA and a 330 Ohm resistor with a 5V supply will give about 8.5mA (assuming a 2.2V drop), which is plenty.

It's really a "lazy" choice that will work well in "most" situations.


Controlling Protoneer CNC shield without PC I'm building an small CNC using Protoneer CNC shield, GRBL and Arduino UNO.
With this I need to connect the board to PC and send G-Code from there.
My question is, is it possible to use the arduino itself to control the CNC shield?
If yes how?
If not is there any other way to send commands other than USB (as Arduino's USB port is not a host)

Thanks

An Arduino can talk directly to a shield, independent of a PC.

This will, however, need a way to tell your Arduino to do it's thing. Depending on what you want it to do, this may require nothing ("send this pre-defined g-code as soon as you are turned on"), a memory card of some sort, one or more pushbuttons, or even a small screen. I have seen several 3d printers with memory cards, buttons (usually up/down/select/back), and a small screen that, once set up, can print anything you can load onto a memory card.

There are other forms of communication, too - ethernet, wifi, etc., which you can use, with appropriate shields.

In the end, of course, you still have to design your object - 3d graphics are well beyond the ability of an Arduino, so there will still be some form of computer involved.


Why is there already text in the serial monitor before the Arduino initializes? I have encountered this several times before and I would like it if someone was able to give an explanation. In almost any sketch that I've ever created with Serial communication involved, I notice that I will get text that seemingly appears before the void setup() function has run. For example, I have the simplest sketch below where this occurs.

void setup(){
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Welcome");
}

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

If I upload this to one of my Arduino Megas, I will often get the output in the serial monitor:

WelcWelcome

When I open the serial monitor to view the output, the "Welc" is already written and then the rest of the "Welcome" come in a few moments later. If I close and re-open the serial monitor or reselect the baudrate setting within the serial monitor, the serial monitor clears, restarting the Arduino, and printing only "Welcome" to the screen without the "Welc", as I would expect.

However, if I upload the sketch, then disconnect-reconnect the Arduino-USB cable from the computer, and open the serial monitor, there is no leftover bytes printed to the screen like before.

The exact bytes leftover that appear before the void setup() function is called varies from upload to upload. Can anyone give me an explanation and is there a way to avoid the leftover bytes ? Thank you.

It's because the Arduino has started running the sketch and placed data into the USB chip's buffer. You then open the serial monitor which then opens the serial port thus resetting the Arduino. So the sketch runs again.

It only resets the Arduino, not the USB interface chip, so you get what was in there from the first execution plus the new text from the second (post-opening) execution.

You cannot "avoid" the extra bytes, that's just the way things are. The Arduino resets. There are buffers in various places. You have no control over those buffers.

As a side note: the serial monitor is completely disgusting. If you want to do things properly use a proper terminal emulator, then you can use ANSI control codes to do things like clear the screen, move the cursor around, apply colour, etc.


Unable to upload to Arduino Due using version 1.6.8 of SAM tools; bossac.exe throwing an error I can successfully see the Arduino Due when I plug it in. I can compile the code, but when I attempt to upload it to the board I get the following error:

C:\Users\user\AppData\Roaming\Arduino15\packages\arduino\tools\bossac\1.6.1-arduino/bossac.exe
        -i -d --port=COM4 -U false -e
        -w true
        -b C:\Users\user\AppData\Local\Temp\build6683778295083335366.tmp/_50key_driver.cpp.bin
        -R bossac.exe: extra arguments found
    Try 'bossac.exe -h' or 'bossac.exe --help' for more information

I finally figured out the problem. This occurred on both a Mac and PC (Windows 10).

This error occurred because of the true after the -w switch. To fix it I modified the package to tell the IDE not to use that switch.

Go to: %USER_PROFILE%\AppData\Roaming\Arduino15\packages\arduino\hardware\sam\1.6.8 (where %USER_PROFILE% is your windows user directory, for me it was C:\Users\user) in Windows Explorer.
Make a copy of the platform.txt file (I called it platform_backup.txt).
Open the file platform.txt with Word Pad (it had Unix line endings in my environment), search for the string:

tools.bossac.upload.pattern="{path}/{cmd}" {upload.verbose} --port={serial.port.file} -U {upload.native_usb} -e -w {upload.verify} -b "{build.path}/{build.project_name}.bin" -R
This was 3rd line from the bottom for me, and remove the text between the quotes "{upload.verify}". It should now look like this:

tools.bossac.upload.pattern="{path}/{cmd}" {upload.verbose} --port={serial.port.file} -U {upload.native_usb} -e -w -b "{build.path}/{build.project_name}.bin" -R
Restart the IDE so it can re-read the file you just edited. You'll now be able to upload to the Due.


How Do I Control the Onboard LEDs of My Arduino Nano 33 BLE Sense? I picked up my Arduino Nano 33 BLE Sense for the first time in a while and ran the classic "Blink" sketch to make sure it was alright. After slight usage, I wanted to play with the onboard LEDs. When I run the following code, the onboard LED does not turn on:
#define RED 22

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

void loop() {
    digitalWrite(RED, HIGH);
}

However when I run the following code, the onboard LED does turn on and stays on - it doesn't blink:
#define RED 22

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

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

What's happening? Is my Nano busted?

There are 3 LEDS on the Nano 33 BLE:

A power LED on pin 25 (yes, you can turn off the power LED programatically);
A built-in LED on pin 13;
An RGB LED with red on pin 22, green on pin 23, and blue on pin 24.

In the variant file, they are given names:
#define PIN_LED     (13u)
#define LED_BUILTIN PIN_LED
#define LEDR        (22u)
#define LEDG        (23u)
#define LEDB        (24u)
#define LED_PWR     (25u)

The power LED and the built-in LED are active-high, ie. you need to set their pin to HIGH to turn these LEDs on. The three LEDs in the RGB LED, however, are active-low.
This isn't well-documented as far as I know, and some example code snippets have it wrong too. A quick look at the schematic helps.
Also, as StarCat mentioned, you need two delay()s to make an LED blink.


How do I convert this program to assembly from c++ I am trying to implement a program in assembly code for an Arduino UNO. A potentiometer is used on an ADC pin for variable time (t). LED1 flashes for t seconds, then stays on for t seconds, then goes off and another LED(LED2) goes on for t seconds and then the cycle repeats (t is variable time that comes from potentiometer). I have a working program in c++ but I want to convert it to assembly. I have just started learning assembly and am not very good at it.

The part I am really stuck on is the analogRead() function. I do not know how to implement this on assembly. Anyone know how to do this?

#define led 3
#define led2 2

void setup()

{

Serial.begin(9600);

//initializing pins
pinMode(led,OUTPUT);

pinMode(led2,OUTPUT);

}
void loop()

{

// read the input on analog pin 0:
int sensorValue = analogRead(A0);

// Convert the analog reading(which goes from 0 - 1023) to a voltage(0-5V):
int voltage = sensorValue * (5.0 / 1023.0);

// print out the value you read:
Serial.println(voltage);

for(int i=0;i<2*voltage;i++)

{

digitalWrite(led,LOW);

delay(100);

digitalWrite(led,HIGH);

delay(100);

}

//red stays on
digitalWrite(led,HIGH);

delay(voltage*500);

digitalWrite(led,LOW);

//green stays on
digitalWrite(led2,HIGH);

delay(voltage*500);

digitalWrite(led2,LOW);

}

The obvious solution for converting any program to assembly is... to
compile it! You can disassemble the resulting binary with a command
like:

avr-objdump -S -C the_program.elf > the_program.lss

This will output a listing of the program, with the original source
interspersed with an hex dump of the binary and the corresponding
disassembly.

  The part I am really stuck on is the analogRead() function.

Here it goes:

000003a6 <analogRead>:
 3a6:   8e 30           cpi r24, 0x0E   ; 14
 3a8:   08 f0           brcs    .+2         ; 0x3ac <analogRead+0x6>
 3aa:   8e 50           subi    r24, 0x0E   ; 14
 3ac:   87 70           andi    r24, 0x07   ; 7
 3ae:   20 91 00 01     lds r18, 0x0100 ; 0x800100 <__data_start>
 3b2:   90 e4           ldi r25, 0x40   ; 64
 3b4:   29 9f           mul r18, r25
 3b6:   90 01           movw    r18, r0
 3b8:   11 24           eor r1, r1
 3ba:   82 2b           or  r24, r18
 3bc:   80 93 7c 00     sts 0x007C, r24 ; 0x80007c <__TEXT_REGION_LENGTH__+0x7e007c>
 3c0:   80 91 7a 00     lds r24, 0x007A ; 0x80007a <__TEXT_REGION_LENGTH__+0x7e007a>
 3c4:   80 64           ori r24, 0x40   ; 64
 3c6:   80 93 7a 00     sts 0x007A, r24 ; 0x80007a <__TEXT_REGION_LENGTH__+0x7e007a>
 3ca:   80 91 7a 00     lds r24, 0x007A ; 0x80007a <__TEXT_REGION_LENGTH__+0x7e007a>
 3ce:   86 fd           sbrc    r24, 6
 3d0:   fc cf           rjmp    .-8         ; 0x3ca <analogRead+0x24>
 3d2:   80 91 78 00     lds r24, 0x0078 ; 0x800078 <__TEXT_REGION_LENGTH__+0x7e0078>
 3d6:   20 91 79 00     lds r18, 0x0079 ; 0x800079 <__TEXT_REGION_LENGTH__+0x7e0079>
 3da:   90 e0           ldi r25, 0x00   ; 0
 3dc:   92 2b           or  r25, r18
 3de:   08 95           ret

Now, in order to more easily make sense of it, you need to know what all
those magic numbers mean. The command

avr-nm -nC the_program.elf

will dump the symbols associated with every RAM and flash address. In
order to tell those apart, 0x800000 is added to every RAM address. This
will tell you that, in this specific program, the RAM address 0x0100
is actually the address of the variable analog_reference from the
Arduino core library. Thus, you can replace the line

 3ae:   20 91 00 01     lds r18, 0x0100 ; 0x800100 <__data_start>

by

    lds  r18, analog_reference

Then you can use the datasheet to get the names of the memory-mapped IO
registers, and the names of the bits from those registers. I have done
all this for you, so here is the cleaned-up disassembly of
analogRead():

analogRead:
    cpi  r24, 14
    brcs 1f
    subi r24, 14
1:  andi r24, 0x07
    lds  r18, analog_reference
    ldi  r25, 1<<REFS0
    mul  r18, r25
    movw r18, r0
    clr  r1
    or   r24, r18
    sts  _SFR_MEM_ADDR(ADMUX), r24
    lds  r24, _SFR_MEM_ADDR(ADCSRA)
    ori  r24, 1<<ADSC
    sts  _SFR_MEM_ADDR(ADCSRA), r24
2:  lds  r24, _SFR_MEM_ADDR(ADCSRA)
    sbrc r24, ADSC
    rjmp 2b
    lds  r24, _SFR_MEM_ADDR(ADCL)
    lds  r18, _SFR_MEM_ADDR(ADCH)
    ldi  r25, 0
    or   r25, r18
    ret

If you compare this with the source code of analogRead(), it
should now make perfect sense.

  I am trying to implement a program in assembly

Now, if you want to write the assembly yourself, that's a whole
different story. If you allow yourself the use of the Arduino core, then
you can simply

    ldi r24, 14  ; pin A0 is pin 14
    call analogRead

If you don't want to rely on external libraries, and really write
everything yourself, it's going to be a lot harder. I suggest you do
this as a two-step process:

Step 1: Learn how to program the ATmega328P in plain C, at the
register level, using no library other than the avr-libc. You can start
by reading this short tutorial about direct port access.
But then you should quickly move on to studying the
datasheet and the manual of the avr-libc. Yes,
that's a lot to digest. I hope you didn't expect this to be quick and
easy. But note that, on those documents, you can skip all the chapters
related to functions you are not going to use.

  I am really stuck on is the analogRead() function.

In the specific case of your example program, you don't need a version
of analogRead() that can read any pin with any reference. You can
instead write a simpler version that just reads the currently selected
pin using the currently selected reference:

int simple_analog_read(void)
{
    ADCSRA |= 1<<ADSC;                    // start the converion
    while (ADCSRA & (1<<ADSC)) continue;  // wait till it's done
    return ADC;                           // return the reading
}

Of course, this assumes you have appropriately initialized the ADC.

  int voltage = sensorValue * (5.0 / 1023.0);

You really, really don't want to implement something like this in
assembly. The AVR hardware supports neither floating point nor
divisions. All this is handled by the compiler through supporting
libraries, and they are not simple. What you really want is something
like

int voltage = (sensorValue * 5) >> 10;

which is incidentally more correct, as the scaling factor is 5/1024, not
5/1023 (see the datasheet).

Step 2: Learn assembly, and rewrite your low-level C code in
assembly. If your C code is low-level enough this should not be too
hard. As a learning aid, you can ask the compiler to do it for you and
then try to make sense of what it did. If you just try to compile the
simple_analog_read() function I wrote above you will see the
translation to assembly is almost trivial.


Unable to see SPI clock in oscilloscope I am using the following code and when I am probing pin 13(SCK), I can't see any clock signal in the oscilloscope.

#include <SPI.h>
int SCS=10;
int SI=11;
int SCLK=13;
int EXTCOMIN=4;

void setup()
{
 pinMode(SCS,OUTPUT);
 pinMode(EXTCOMIN,OUTPUT);
 pinMode(SCLK,OUTPUT);
 digitalWrite(SCS,HIGH);
 tone(EXTCOMIN,50);
 SPI.setClockDivider(SPI_CLOCK_DIV16);
 SPI.begin();
}

void loop()
 {
 }

(META: This question has been answered in the comment section of the question itself. (And I'm also unable to comment to say that he should answer his own question...) That's why I'm putting this answer here.)

You might want to look into the basics of SPI, the clock will only oscillate when there is an actual data transaction in progress. (This will prevent desynchronisation by a bit. And will make both sides know when data is being send. Often along with a SS)
You can check this by continiously sending something in your code and then probe the clock pin with an ossciloscope.

You might want to accept this as an answer, so that nobody it's clear this question is already answered.


Arduino pro mini not compiling after changing fuse to 128khz I used Arduino UNO as ISP to change the fuse setting of Arduino Pro Mini. Using avrdude cmd, I successfully changed it to 8MHz setting. Due to curiosity, I decided to try changing it to 128kHz. But that ends up me being unable to further program it. The Pro Mini still works but just cant change fuse through avrdude cmd, burn bootloader and upload. Does 128kHz really leave atmega328p like that?

On one computer, the below error appears.

avrdude: stk500_recv(): programmer is not responding

On another computer, the below error appears

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

There are actually more errors because I trial and error different ways to solve it, i.e Nick Rammon's Atmega_Board_Programmer, cmd command with varying parameters (baud rate, programmer), inserting capacitor on UNO. But I dont remember every one of them because the not in sync:resp=0x.. differs from time to time

There is one method which I have not try, high voltage programming mode. I would try it out if it was detachable but atmega328p on Pro Mini is SMD. Is it possible to high voltage program on Pro Mini? Ultimately I am stuck.

Ignoring what I have done, I would once again like to try out every method you guys recommend. Hopefully everything can be step by step and the thing I want to know most is the setting of 'Board', 'Processor' and 'Programmer' in Tools.

I would give my best response possible to you guys who is willing to help me out. Thank you

At that clock rate each programming clock cycle must be at least 3 system clock cycles, which means that the programmer either must use a much slower SPI rate, 42kHz or less, or it must provide an external pulse train to clock the device manually. Modify the ArduinoISP sketch to either use a slower clock or to provide an external clock to the target.


Control two stepper motors simulatenously? I'm using Arduino Mega 2560, A4988 motor driver for 5 stepper motors. There are X1, X2, Y, Z, A axis, and if I control Y and Z at once, it works. But when I just change axis from Y&Z to X1&X2, only X1 stepper motor spins. X1&X2 need to move at once(simultaneously) due to they are connected in single bar.

My Arduino IDE code is,

==============================

const int X2step = 5;

const int X2dir = 4;

const int X1step = 3;

const int X1dir = 2;

void setup() {

    pinMode(X1step,OUTPUT);

    pinMode(X1dir,OUTPUT);

    pinMode(X2step,OUTPUT);

    pinMode(X2dir,OUTPUT);

}

void loop() {

    digitalWrite(X1dir,HIGH);

    digitalWrite(X2dir,HIGH);

    for(int x = 0; x < 4000; x++) {

        digitalWrite(X1step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X1step,LOW);

        delayMicroseconds(2000);

        digitalWrite(X2step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X2step,LOW);

        delayMicroseconds(2000);
    }

    delay(1000);

    digitalWrite(X1dir,LOW);

    digitalWrite(X2dir,LOW);

    for(int x = 0; x < 4000; x++) {

        digitalWrite(X1step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X1step,LOW);

        delayMicroseconds(2000);

        digitalWrite(X2step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X2step,LOW);

        delayMicroseconds(2000);
    }

    exit(0);

=================================================

Any suggestion would be helpful for me. Thanks.

You likely have other issues to boot based on what you said about only X1 moving, but first I suggest resolving the bug in your code.  It appears to be that you have delays between your digital writes to x1, x2. And set their directions to the same.

At the very least you should be writing to X2 step every time you write to X1 step.  If your wiring is identical and the motors are essentially attached mirrored on opposite sides of a shaft, don't forget to set the directions opposite before you start sending steps. (If they are on opposite sides of the shaft, one spinning counterclockwise means the other spins clockwise.  You can also play wiring tricks with what coil goes where and how, but identical is simpler.)

digitalWrite(X1dir,HIGH);
digitalWrite(X2dir,LOW);

Or

digitalWrite(X1dir,LOW);
digitalWrite(X2dir,HIGH);

Then step it like

digitalWrite(X1step,HIGH);
digitalWrite(X2step,HIGH);

delayMicroseconds(2000);

digitalWrite(X1step,LOW);
digitalWrite(X2step,LOW);

delayMicroseconds(2000);
...