Problem with simple coding for PLDuino: trying to turn relay on and off I am writing the following, simple code to try to turn a relay in the PLDuino on and off, and it is giving me warnings and not compiling/uploading. Any help would be greatly appreciated. Here is my code:

#include <PLDuino.h>
using namespace PLDuino;

void setup()
{
  // A necessary call.
  // It sets pin modes according to their function.
  PLDuino::init();
}

void loop()
{
  // Simple switch RELAY3 on and off with 2 second timeout.
  digitalWrite(PLDuino::RELAY3, HIGH);
  delay(2000);
  digitalWrite(PLDuino::RELAY3, LOW);
  delay(2000);
}

I have installed the proper libraries. Here are the warnings I am getting:

WARNING: Category 'Graphics' in library PLDTouch is not valid. Setting to 'Uncategorized'
WARNING: Category 'General' in library PLDuino-Library is not valid. Setting to 'Uncategorized'
WARNING: Category 'Graphics' in library PLDuinoGUI is not valid. Setting to 'Uncategorized'
Sketch uses 1702 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
avrdude: ser_open(): can't open device "\\.\COM4": The system cannot find the file specified.

avrdude: ser_drain(): read error: The handle is invalid.

avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: ser_recv(): read error: The handle is invalid.

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

For the library warning, you'll need to add / edit library.properties to those folders to specify a valid category.

This is an example library.properties to give you a feel for the structure (I found this particular one here).

name=TMRpcm_PLDuino
version=1.0
author=TMRh20
maintainer=digitalloggers
sentence=PCM/WAV Audio playback (USE_TIMER2 enabled)
paragraph=Play WAV audio files from SD card using AVR (UNO,Nano,etc) based devices.
category=Communication
url=https://github.com/digitalloggers/TMRpcm_PLDuino
architectures=avr

However, these are just warnings, and don't seem to be the cause of your problem.

Your actual problem in this case seems to be that it's trying to upload the sketch via COM4 and it can't find the PLDuino on that port.


How to build a high-frequency (>20kHz) driver for LEDs? I'd like to build a LED lighting for my house. I've made preliminary tests and I've realized that my 12V transformer emits a considerable electric hum at the Arduino's PWM frequency range (PWM signal from Arduino gets amplified by external amplifier powered by the transformer).

I know, that I can reduce the audible noise if I will drive the PWM at higher frequency, beyond the human ear's audible range.

AFAIK Arduino itself is not able to give me 8-bit PWM at the >20kHz range. Do you know any feasible hardware high frequency PWMs that will work with the Arduino?

Just change the timer prescaler to a lower value.

E.g. timer2 (PWM pins 3 and 11) has the prescaler set to clock/64 and runs at around 500Hz. So changing it to clock/8 will result in 4kHz. (Sorry, no clock/16 available).

TCCR2 &= ~_BV(CS22);//clear CS22 bit
TCCR2 |= _BV(CS21);//set CS21 bit


Why would the resistor be after the LED in this project? This is project 2 of their official arduino projects book called "Spaceship interface". I understand resistors normally reduce voltage so the LEDs don't burnout but here 5v is coming from either digital 3, 4, or 5 and it seems like it goes right into the LED before going through a resistor as it goes back to ground. This makes no sense to me.

It does not matter if a resistor is before or after a component, see the circuits below.

The resistor reduces the current, and this is true for the path where the resistor is in (until the interconnections before/after the resistor). In the examples there is only one path.

simulate this circuit – Schematic created using CircuitLab


How does one design for the power on transient conditions? Following on from the question Reset an Arduino UNO by an command (software) and the excellent answer provided by mpflaga, the comment addressing option (1) suggests that there are design considerations for connecting an output pin to the RESET pin.

  Option 1. or a variant can be a clean enough way to do this as long as
  power on transient conditions are designed for.
  - Russell McMahon

or more ominuously

  From everything I've read, the first option is not recommended. - sachleen

Could someone tell me exactly what those considerations are? Is it that it is not as simple as connecting the two with a jumper cable - is additional circuitry (i.e. an RC timer) required, or is there a software solution?

I find the latter option unlikely as the device is rebooting, so unless the software fix is to ignore hardware interrupts (since a RESET is simply that, and the state of the output pins is unlikely to be known, or stable at reboot) for a few mS after reboot, I presume that a hardware fix is required.

Atmel specifically recommend against driving /RESET low from an output pin, because the first thing that the reset process does is set all pins to high impedance, thus cancelling the reset pulse before the recommended reset pulse length has elapsed.

The recommended use of the watchdog timer does not suffer from these limitations. It is designed to reset the board (or there would be no purpose to having it) and it does a proper reset (unlike jumping to address 0x0000).

Reference

Atmel knowledge base - Software Reset

  If you want to perform a software reset of your AVR you should use the internal Watchdog. Simply enable it and let it time out. When the Watchdog triggers it resets the program counter back to 0, clears all the registers and performs all the other tasks. This operation gives the same result as pulling the RESET line low.

  You should not try to:

  Use another pin of the AVR to pull the external RESET line. The pins of the AVR are tristated halfway through the minimum reset time, this releases the RESET line and hence nothing happens.
  Jump to program location 0. Jumping to program location 0 does not clear all the registers and hence you do not have a "clean" reset.

Their suggested code to reset the processor:

#include <avr/io.h>
#include <avr/wdt.h>

#define Reset_AVR() wdt_enable(WDTO_30MS); while(1) {}

int main(void)
{
Reset_AVR();
}


Arduino Grounding Issue I have a project that turns a LED strip on and off using capacitive touch.  The project uses an Arduino Micro as the brain and a 12v wall wart to power everything.  I have the Arduino ground and negative from the power supply running to a common ground.

Everything works as expected during testing and the Arduino is connected via USB to my computer; however, when I unplug the USB and connect the circuit to the light installation, the lights just flicker on and off.  When I touch my finger to the negative/ground (and presumably provide common ground), everything works as expected.

It seems obvious to me that I have a grounding issue, but really do not know how to proceed. Is there a specific technique for grounding from a wall wart? Do I need to somehow pull the ground/negative down? I feel like there is something obvious that I am missing.

Thank you in advance for any and all help.

Seems like there is a problem in your wall wart, actually some people are having problems using wall wart with arduino. The problem is with the circuit of thre arduino regulator and with sime ripple variances with de wall wart, i sugest you to setup in your project a regulator (7805) and see if the problem is gone. This is by far problem not just with grounding, but with the power suply in general. I was used to make PIC projects and once it was happening exatly the same that happaned to you but the microcontroller started to work when i put my hand or finger close without even touching it :x. Crazy thing. If the power supply isn't well suited, the arduino enter in continous reset looping because of supply noise. So just put an external regulator, an maybe an extra capacitor (generally 10 nF) in arduino micro power supply rais (VCC-GND). Here's my tip. Good look man, tell me if it worked :)


Extremely unstable analogRead() on Arduino Nano when powered from an external source I'm doing a really simple project with an Arduino Nano and found a problem.
The circuit is a simple temperature sensor and a tension read from an analog pin everything showed on a Nokia 5110 LCD.
When the Nano is connected to the USB everything works and the reads are perfect.
When I install the circuit on my car taking the 12V to the Vin and the GND from the centraline everything goes bad: I certainly know that the 12V is obviously not stable and oscillates a lot (between 12V and 14V).
What can be the solution? Should I add some ref or should I regulate the input tension to maintain it stable to a certain quantity?

You can use a branded 5 V charger made for cars. You can directly connect this to 5 V pin of the Arduino.
By doing this:

you are protecting the Arduino from the noise as well as high voltage spikes coming from the car 12 V supply
protecting yourself and others coming in contact with the Arduino or the sensors connected to the Arduino.

You can also

consider filtering the analog data read
protection circuits such as surge protection diodes or a 5.7 V Zener across 5 V and Ground of Arduino


Do I really need Ramps 1.4 for laser engraver I'm making 2-axis laser engraver like system. Arduino waits command from pc, on receive moves laser to next coordinate and send current coordinate to pc.

I have 3 step motors and I'm controlling them with Arduino Uno which is connected to A4988 drivers which is on breadboard. But almost all samples using Ramps. Do I miss something?

Ramps 1.4 is one of the proof of concept standards for 3D printer systems. It is a motherboard mostly runs Marlin firmware on it. I advice to to take a look at the firmware if you didn't yet. It is also supporting many motherboards, hardware.

When you open the configuration.h file in the firmware and search for this definition #define MOTHERBOARD you will be seeing many options available.

After all, the firmware is the key factor. It contains many engineering solutions in it. So, you shouldn't re-invent the wheel.
All you have to do is to adapt it with some tweaks as per your design specifications.

But, I would worry more about your motherboard (Arduino Uno)
if your design is relatively simple, using less memory and IO pins, it may be just fine. I would consider Mega 2560 instead If I were you.

Good luck with your project.


How time intensive or how long can an ISR be? I would like to code my ISR to be time intensive or interrupt the main program for atleast 1 or more seconds. My goal is to verify that if I am reading a sensor in the main loop, would it stop reading the sensor when the code is interrupted and for how long. I have trying to call various functions from the ISR like to turn on the motor but everything is instantaneous.

How long can an interrupt be?

If you don't want anything else to happen, then as long as the time between successive interrupts.

  would it stop reading the sensor when the code is interrupted and for how long.

While the interrupt is running nothing else can happen in software. Absolutely nothing. Only one thing ever happens at once - either your main loop or the interrupt. For the entire duration of your interrupt everything else is put on hold.

That includes things that rely on other interrupts to function, such as serial communications, millis() and delay(), etc. That means using such functions from within your interrupt handler is a big no-go.

It is generally very very bad practice to have an interrupt blocking for more time than absolutely necessary (a few milliseconds or even less). If you need to have things taking a long time then you should consider breaking them down into smaller operations and doing different sections at different times through different means.


Can I prevent the Stepper library from holding the motor? I'm using the Stepper library to control a single stepper motor. When the Arduino is not running the motor it is holding the motor shaft in place. For my application, this is very wasteful and puts unnecessary strain on the motor.

Is the Stepper library supposed to do this or is something else up with my circuit? Can this behavior be overridden?

use disable output class in  accelstepper library.
http://www.airspayce.com/mikem/arduino/AccelStepper/


Air data rate nRF24L01 I'm using two nRF24L01 to communicate with each other. I did the right setup and they worked fine, however I wanted to change the air data rate to a lower value, for more stability, as the datasheet says.

How can I setup the configuration for this?

After a small research I knew that you can change this using RF_DR
to change the value of the transmission, but I didn't really know how I could exactly write the correct code for this.

Another question: does this effect the range of the module? Or does it only affect the stability? And if not, then which code can I use to extend the range of these two modules ?

Increasing stability will increase the (usable) range. At least a bit. You could try decreasing the packet size, to make it even more reliable. There is no way to increase the output-power (only decrease).

You could try different channels, and see which one gives you the best range in your application.

After that you have to get NRF24 modules, with external antennas and amplifiers.


Arduino Mega, ST7920 using COSA I am trying to learn and understand the COSA Library using a 12864ZW (ST7920) 128X64 LCD Display. Right now I am able to use the LCD using the u8glib but also found that COSA has a library for the ST7920 Display, I originally used this tutorial to get things working.

The main problem that I have now is in the ST7920 Documentation there is a schematic that shows how to hook up a ST7920 Compatible LCD. The first tutorial only uses 3 lines from the Mega and the Cosa is using what looks like 6 lines.

Looking at the header file, it looks like it is derived from the HD44780 Class and what I can gather is pins 16 and 4 are hard coded for something? I am not quite clear on how to use the Cosa version of the library. Can someone please give me a explanation and perhaps a explanation on how to get this working using Cosa?

The Cosa ST7920 library uses text mode only (16X4). The ST7920 class is controlled though an adapter. There are several adapters available depending on how you wish to connect to the Arduino. They range from parallel 4-bit to SPI with shift register. The adapters implement the interface HD44780::IO. There are several LCD examples. The CosaLCDbench shows the possible configurations with LCD and Adapters. Please see the file for further details.


Random numbers recived by wifi shield So I am sending a web request to a server, but for some reason the result is the number: 728484804749464932504848327975131083101114118101114583213106897116101583284117101443250483268101993250484954325049585054585249327177841310671111101161011101164584121112101583211610112011647104116109108131067111110116101110116457610111010311

Any ideas?

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C Lcd(0x27, 16, 6);

#include <SPI.h>
#include <WiFi.h>

char ssid[] = "AESRO2-2.4G";
char password[] = "EA8TDKNFGE";

int status = WL_IDLE_STATUS;

WiFiClient client;

String serverReturn;

String page[]
{
  "Flashlight",
  "Message",
  "S.O.S"
};
void displayPage(int pageNumber)
{
  Lcd.clear();
  Lcd.print(page[pageNumber]);

  Lcd.setCursor(0,1);
  Lcd.print("[Open]");
  Lcd.setCursor(10, 1);
  Lcd.print("[Next]");
}
int currentPage = 0;
int lastPage = 1;

void setup()
{
  Serial.begin(9600);
  pinMode(6, OUTPUT);
  pinMode(8,OUTPUT);

  Lcd.begin();

  Lcd.print("BrickOS V5.0.0");
  digitalWrite(6, HIGH);
  delay(300);
  digitalWrite(6, LOW);

  delay(1000);

  if(WiFi.status() == WL_NO_SHIELD)
  {
    Lcd.clear();
    Lcd.print("No wifi shield");

    while(true);
  }

  String fv = WiFi.firmwareVersion();
  if(fv != "1.1.0")
  {
    String secline = fv += "->1.1.0";
    Lcd.clear();
    Lcd.print("Firmware update");
    Lcd.setCursor(0,1);
    Lcd.print(secline);

    while(true);
  }

  while(status != WL_CONNECTED)
  {
    Lcd.clear();
    Lcd.print("Connecting to");
    Lcd.setCursor(0, 1);
    Lcd.print("network...");

    status = WiFi.begin(ssid, password);

    delay(3000);
  }

  Lcd.clear();
  Lcd.print("Connected to:");
  Lcd.setCursor(0, 1);
  Lcd.print(ssid);
  delay(1000);
}

void loop()
{
  if(lastPage != currentPage)
  {
    if(currentPage > sizeof(page))
    {
      currentPage = 0;
    }
    displayPage(currentPage);
  }
  lastPage = currentPage;

  serverReturn = "";
  while(client.available()) {
    serverReturn += client.read();
  }
  client.stop();
  if(client.connect("www.nightfall.huskyclick.info", 80))
  {
    client.println("GET /msg.php?action=check&ID=1 HTTP/1.1");
    client.println("Host: nightfall.huskyclick.info");
    client.println();
  }
  else
  {
    Lcd.clear();
    Lcd.print("Failed to check");
    Lcd.setCursor(0, 1);
    Lcd.print("for messages");
  }

  Serial.println(serverReturn);

  if(serverReturn != "false" && serverReturn != "")
  {
    digitalWrite(8, HIGH);

    Lcd.clear();
    Lcd.print("Message received!");

    digitalWrite(6, HIGH);
    delay(500);
    digitalWrite(6, LOW);

    delay(1000);

    Lcd.clear();
    Lcd.print(serverReturn);

    delay(5000);
  }

  delay(5000);
}

The fault lies here:

while(client.available()) {
  serverReturn += client.read();
}

client.read() returns an integer. That integer is either the ASCII code of the next character in the buffer, or -1 if there are no characters in the buffer left to read.

You then append that integer to the end of a String which gets converted to the ASCII representation of that integer before being appended.

So the string HTTP, for instance, which is ASCII characters 72, 84 (twice) and 80 ends up as "72848480".

Instead you need to cast the integer to a char before appending:

serverReturn += (char)client.read();

Or better still don't use any String variables at all and parse the data as it comes in pulling out any information you need to at the time it arrives.


What's on an Arduino board? Can i build one of these boards myself? My question is: What is on an Arduino board besides the microcontroller?

When I first built my first Arduino clone, I fount very useful the Fritzing examples (boards and schematics). http://fritzing.org/home/

Mind that in order to upload sketches, an FTDI module is very handy (unless you use ISP via another Arduino board).

In any case, I should recommend you to build an Arduino clone on a breadboard, before trying soldering.

Good luck.

Additionally, you may use this picture (this is how  I create an Arduino on breadboard):

External power (battery) is connected to the screw pins (bottom left of the breadboard).


L298 Motor Driver not showing Red light when connecting power supply I recently bought an L298 motor driver module for controlling 2 motors(5v each).
When i connect the power supply(which is a normal RC car battery holder(3)) the red light doesn't light up.
Instead if i connect the +ve to the 5v on the motor driver, the red light is glowing, but the motors don't work.

You need to do math on the power consumption as arduino uno takes takes 5 V 500 mA at least for it to work. That is why it can be powered by USB cables too.
Now if you try calculating power consumption on the motors you would understand that the power you are giving is nowhere enough for the arrangement to work or you could have been able to run the motors without the motor driver.
Try upgrading the power you are giving.


Leostick Receiving message from Uno using USB jumpers cables I have a Arduino Uno which is looping over Serial.println("$testmessage"). Connected to this is a USB cable that i have cut and soldered male jumper leads to . I need to receive this message ("$testmessage") from the Uno using this USB cable without using the leosticks usb connector. After receiving the correct messgae from the Uno i plan to use Serial to send data from the leostick to my pc.

I'm stuck trying to figure out how to receive this message from the Uno.

Currently the the USB 5v and ground is connected to the leosticks 5V, GND pins. The Uno powers on and the the tx led is flashing every 100 milliseconds.

Can i just plug the green and white wires from the USB cable into D0&D1 and except it to work?

(Uno plugs into usb cable in the image)
http://imgur.com/jxiKJMa

I don't think this has any chance of working. You can't use USB to interface between the two devices, as the Leostick can't work as USB host. Your best bet is to use (software) serial.


Writing and reading an ID to/from an Arduino reliably I need a way to both ID (a sketch/compiled hex) and later on, identify based on this ID the project that got uploaded to my Arduino microcontroller. As of right now, I have explored multiple options for storing the ID and reading the ID from the Arduino. The ID would be a custom string or later on multiple strings. Here are the 3 options I have been thinking about with their pros and cons:

Option 1:

Writing: A custom function that would be added to every sketch before compilation, containing the ID information and a serial connection setup

Reading: The function would dump the ID over the serial connection using a fixed baud, after this, the projects original serial and baud would be initialized. The microcontroller would need to be rebooted in order for the user to be able to read the ID from it.

Pros: Easy to implement.

Cons: Would require manual or software restart of the microcontroller in order to read the ID

Option 2:

Writing: writing the ID to the EEPROM

Reading: reading the ID from the EEPROM over the serial connection.

Pros: Would probably not interference with the original code

Cons: it wears the EEPROM, it might need its own function in the sketch to read the ID from the EEPROM thus making it a complicated Option1.

Option 3: Editing the HEX file to include a signature

Writing: add the ID to the hex file itself (hex editing), after compiling it.

Reading: dumping the hex file and decoding the string.

Pros: No baud or serial needed to be set?

Cons: Probably slow, can end up producing a bad hex file, hard to implement properly with larger ID-s and structures

Example data:

project="marlin2.1",
config="prusa",
version="8.80",
env1="pin2"

As said, the basic idea is storing an ID but I would late want to expand this and store more information like a struct.  This solution should be able to Target as many Arduino models as possible. I am looking for the best way that I might have missed to achieve this task or any recommendations.

I'd go with #2. If you are concerned that you will eventually burn-out your EEPROM (100.000 write cycles per ATmega328 ds), try writing a macro, which will dictate at which upload you want new ID to be written in EEPROM.
Heck, instead of writing all of these onboard, why don't you maintain an offline lookup database and encode things yourself? It would still require writing to EEPROM but you could encode your information in a couple of ints.


How to convert kitchen timer code into a countdown I found this code for a kitchen timer, it was the closest thing to a countdown. The code is here:

#include <LiquidCrystal.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

signed short minutes, secondes;
char timeline[16];

void setup() {

  lcd.begin(16, 2);
  lcd.print("Chronometre :");

}

void loop() {

  lcd.setCursor(0, 1);
  sprintf(timeline,"%0.2d mins %0.2d secs", minutes, secondes);
  lcd.print(timeline);

  delay(1000);
  secondes++;

  if (secondes == 60)
  {
    secondes = 0;
    minutes ++;
  }

}

How do I convert it properly for it to countdown from 1 minute and 30 seconds?

As a start, you need to initalise the secondes and minutes variables to 30 and 1 respectively.
replace signed short minutes, secondes; with:
signed short minutes = 1;
signed short secondes = 30;

Next thing I notice is that the code you have provided counts up and you have requested that it count down.
Change secondes++; and minutes++; with:
secondes--;
minutes--;

Lastly you need to change the logic for when the secondes and minutes variables reach zero.
If the secondes variable reaches zero but the minutes variable is greater than zero, then you decrement the minutes (using the line of code provided above) and top-up the secondes with 59.
secondes = 59;

You will need to check the value of the secondes and minutes variables using a couple of if...else statements.
if (secondes == 0 && minutes == 0) {
    // insert your timer finished code here
}
else if ( secondes == 0 && minutes > 0) {
    minutes--;
    secondes = 59;
}
else {
    // Error - your code should not reach here.
    // Display an error message on the LCD
}

This if..else statement will need to go at the top of your loop instead of the end.


Enter timing value via keypad for bldc motor spin I am trying to key in the timing for how long the bldc motor needs to spin via keypad. I hope you can help me with this. I'm using delay() to set the timing of bldc motor spin. How do I key in a series of numbers in seconds, and then put it in the delay()?

The idea for this code is to enter the speed and timing via keypad.  After entering the speed and timing, button '#' is used to move the bldc motor according to the speed and timing entered. My question is how do I make my code to compile where speed is keyed in first, timing second then button '#' to run the motor?

Here is my code so far...

#include "Keypad.h"
#include "LiquidCrystal.h"
#include "Servo.h"

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);

Servo myservo;

const byte ROWS = 4; //four rows
const byte COLS = 3; //four columns
char keys[ROWS][COLS] =
 {{'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
  };
byte rowPins[ROWS] = {9,8,7,6}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {5,4,3}; //connect to the column pinouts of the keypad
int count=0;

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print("S:");
  lcd.setCursor (0,1);
  lcd.print ("T:");

  myservo.attach(11);
}

void loop()
{
    static char buffer[4], spintime[4];
    static byte i = 0, a = 0;
    char key = keypad.getKey();

    // i < 3: prevent buffer overflow
    if  ('0' <= key && key <= '9')   // this is for speed entry
    {
        buffer[i] = key;
        ++i;
        buffer[i] =0;  // null-terminate buffer
        lcd.setCursor (2,0);
        lcd.print(buffer);
    }

     if  ('0' <= key && key <= '9') // this is for timing entry
     {
        spintime[a] = key;
        ++a;
        spintime[a] =0;  // null-terminate buffer
        lcd.setCursor (2,1);
        lcd.print(spintime);
    }
    else if (key == '#')            // this is to run the motor after speed and timing are entered
    {
        int value = atoi(buffer);
        myservo.write(value);       //speed of motor
        int timing = atoi(spintime);
        delay (timing*1000);        // keep the motor spin for ( timing entered) second
        myservo.write(0);
        i = 0;
    }
}

As I understand it, you want to enter the speed, then the time, then '#'.

Let's imagine you want a speed of 22 and a time of 3.  The device will see 2, 2, 3, #.  How will it know whether you're asking for a speed of 22 and a time of 3, or a speed of 2 and a time of 23?  Simple answer: it cannot know.  So we need to find a way to tell it.

My suggestion: we'll enter speed followed by *, and time followed by #.  (There are other possible solutions to this.)

We also need to decide the longest number the user can enter, and what happens if they enter a longer one, or if they don't enter one at all?  Let's say the longest number is 3 digits, and if they enter a longer one, we will ignore the extra digits.  So if they enter 123456789#, we will register 123#.  (Again, there are other solutions.)

There's some stuff in your code about an LCD, but you don't mention it in the question, so I have ignored it.

Lastly, I am assuming your code to drive the motor and read keys is correct.

Here's some loop code which I hope will do the above.  It will read numbers until it finds either a * or a #, convert the number to an integer, and store it as either time or speed.  When it has both speed and time, it will spin the motor and reset the values.

void loop()
{
    // Where we will store the number as we type it.
    // This buffer is large enough for a 3-digit number, pull a null terminator
    char buffer[4];

    // The speed of the motor
    static int speed = 0;

    // The time to spin for
    static int time = 0;

    // Input up to 3 numbers until we find a * or #
    int i=0;
    while (1)
    {
        char key = keypad.getKey();

        // If it's a number AND we have space left, add to our string
        if ('0' <= key && key <= '9' && i<3)
        {
            buffer[i] = key;
            i++;
        }
        // If it's a * or #, end
        else if ('#' == key || '*' == key)
        {
            // Null terminate
            buffer[i] = 0;

            // Convert to an integer
            int value = atoi(buffer);

            // Set the appropriate value
            if ('#' == key) time = value;
            if ('*' == key) speed = value;
            break;
        }
    }

    // If we have both speed and time...
    if (speed > 0 && time > 0)
    {
        // ...spin the motor at the required speed
        myservo.write(speed);
        // ...and for the required time
        delay(time*1000);
        // ...then stop it
        myservo.write(0);

        // Reset the values for next time
        time = 0;
        speed = 0;
    }
}


Why does the Pro Mini 5 v and 3.3 v version have different clock frequencies? It looks like the 5 volt version used the 16MHz external crystal while the 3.3V one uses the 8MHz crystal. I need to use 3.3v as my operating voltage.

Can I just remove the linear regulator and bring in 3.3V. I still have to select the 5V 16MHz version in the Arduino IDE, right?

https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf

The ATMega328p is not rated to operate at 16 MHz on a 3.3v supply.

In practice it may sometimes work, but cannot be considered reliable.

The data sheet will show the actual clock rate vs. voltage tradeoffs, so there might be an intermediate value that is workable for you.

The Arduino toolchain needs to know the CPU clock frequency for the serial baud rates, timing delay code, and any time-based use of the timer peripherals to come out right.

There is a special case where if the configured clock rate and the actual clock rate differ by a factor of two, you may be able to cover that by selecting a similarly wrong baud rate - however, the baud rate in the bootloader was set in comparison to the expected clock frequency when it was compiled before flashing, and the baud rate expected of the bootloader is set in the boards file, so less readily changed than it is in something like the serial monitor.


Button to not run script I'm looking to have a button that, when pressed down, will mean that the script loaded on the Arduino doesn't run. So far I have:

void setup() {
  pinMode(3, INPUT_PULLUP);
  if (digitalRead(3) == LOW) {
    while(1);
  }
  // Beginning the Keyboard stream
  Keyboard.begin();
  // then the rest of the code.

I have a push button soldered to the ground and 3 pin. Could you see what is wrong with the code?

I would do it this way:

void setup () {
    pinMode(3, INPUT_PULLUP);
}
void loop () {
    while (digitalRead(3)==LOW) {}; //do nothing, wait for release button
    // do all my stuff
}

or even better I would use some LED to indicate, that the button is pressed (or released) to have some visual state indicator (or another stuff to do while the button is pressed

void setup () {
    pinMode(3, INPUT_PULLUP);
    pinMode(13, OUTPUT);
    digitalWrite(13,LOW);
}
void loop () {
    while (digitalRead(3)==LOW) {
       digitalWrite(13,HIGH); // let it shine
       };
    digitalWrite(13,LOW);
    // do all my stuff
}

eventually

void setup () {
    pinMode(3, INPUT_PULLUP);
    pinMode(13, OUTPUT);
    digitalWrite(13,LOW);
}
void loop () {
    if (digitalRead(3)==LOW) {
       digitalWrite(13,HIGH); // let it shine
       while (digitalRead(3)==LOW) {
          // do some other stuff
       };
    digitalWrite(13,LOW); // switch indicator off
    // do my regular stuff
}


Arduino Serial Communication with Python: sending an array I am a bit new to both Arduino and Python. My aim is to send commands to Arduino to run a stepper motor. I need to send an array containing the parameters. After consulting many earlier posts like:

https://stackoverflow.com/questions/27639605/send-a-list-of-data-from-python-to-arduino-using-pyserial

Send multiple int values from Python to Arduino using pySerial

I wrote my Arduino code:

long  incoming[3];

void setup() {
  pinMode(13, OUTPUT);
  Serial.begin(9600);
  Serial.println("Ready");
}

void loop() {
  if(Serial.available()) {
    for (int i = 0; i < 3; i++) {
      incoming[i] = Serial.read();
    }
    Serial.println(incoming[0]);
    Serial.println(incoming[0]);
    Serial.println(incoming[2]);
  }
}

And the Python(2.7) code:

from time import sleep
import serial
import struct
ser = serial.Serial('COM6', 9600)

while True:
     ser.write(struct.pack('>iii',2000,10,220))
     print ser.readline()
     sleep(.5)

Now coming to the problem:

The values printed on the Python shell are completely wrong, including negative values.
If I use >BBB instead of >iii, I am getting the correct result, but I can't go beyond 255, the integer limit. There is a small catch here also, the initial two sets are giving minus values and then it becomes alright.
Further, is there any way to interrupt a running void loop?

Any help is deeply appreciated.

If I use >BBB instead of >iii... That's because "B" is a byte. So you end up sending 3 bytes:

struct.pack("BBB", 1, 2, 3)
\x01\x02\x03

"i" is an int and has a size of 4, so you send 4*3 = 12 bytes:

struct.pack("iii", 1, 2, 3)
\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00

Serial.read() reads 1 byte at a time, so you need to read 4 bytes for each value.

Here's a function to read a 32-bit int. The drawbacks of this method are that a) it will block until 4 bytes have been read. And b) there's no way to tell if some data has been lost. There are more robust ways to send data with Start-of-Message, End-of-Message, and Check-sum chars. Also, the function assumes the data is sent with the LSB first. But I'll just put this here as an example.

// Helper macro to merge 4 bytes
#define TO_INT32(a,b,c,d) (((d)<<24)|((c)<<16)|((b)<<8)|(a))
int32_t read_int()
{
  uint32_t result[4];
  for (int i = 0; i < 4; i++) {
    // Wait for data at the port
    while (!Serial.available());
    result[i] = Serial.read();
  }
  return TO_INT32(result[0], result[1], result[2], result[3]);
}


Better way for connecting to Arduino pins to a sensor than jumper cable Well I have an dht21 and arduino mega. Dht21 leads look like this

If I use jumper cable and soldering dht21 leads with jumper cable than plug-in my arduino's socket. it looks like this below image. It dont looks safe. If the device falls to the ground or something, the cables may come out of place or the place may loosen over time. If I solder the cables under the arduino, it will be hard and looks like ugly. What is the best solution to plug-in a sensor to arduino board.

Remember the Arduino is a prototyping system and it should be easy to plug, unplug and move around connectors.
If you want a permanent solution, you should make your own PCB and you will have a huge choice of connectors suited for all imaginable purposes (for example the JST family of connectors).
There are some connectivity systems like the Grove connector that have attempted to standardize connectivity on Arduino and related platforms.


What is the Proper Voltage to supply an enough Current to the Arduino I'm just confused about the supply that I should use in driving my arduino. Is it okay to use a 3.7V with a 1000mAh to supply it?

I will be using a Lilypad Arduino.

Your replies would be a big help to me.

Cheers!

The Technical Specs say that 2.7-5.5V DC is ok so you should be good at 3.7V DC.

Remember though:  Power consumption = Current  x  Voltage

So check that your power supply has enough current available. The current amount used will depend on how many pins you are using. The maximum each digital pin may use is 40mA. 1A (1000mA) will be plenty but mAh (milliampere hours) sounds like a battery specification.

Also, a word from the wise is that some cheap power supplies can be bad (little spikes and dips). If you are having trouble with strange issues it can be a good idea to check the power is ok.


What sensor is used to judge transparency? I want to create a system to separate between an aluminum can and a plastic bottle.

Both are lightweight, so I'm thinking of using the transparency property, meaning that the can is not transparent, but the plastic bottle is.

Will the light sensor work out?

Or would you suggest me another type of sensor I should use?

A light sensor should work. Another option would be an inductive Sensor to detect the Aluminium Can. And if you need to know if there is a Can in your sensor area you can combine it with an IR (or capacitive) Sensor, which should detect both Can types.

So it would be something like this:

if(IRdetect == true){
  if(inductive == true){
    type = alu;
  }else{
    type = plastic;
  }
}else{
  // no Can
}

Some cheap sensors as Example:

Inductive: Banggood
Infrared: Banggood


Answer power IN from two sources Items:

Arduino Uno
Laptop
7.4V 2s LiPo Battery
Neewer 30A ESC

Scenario:

The LiPo powers the ESC while the Laptop USB powers the Arduino. If I unplug the USB from Arduino is loses power (obviously) and when I plug in the ESC to the arduino I get power again to the Arduino. I need the USB plugged in to receive Serial information from the laptop and I need pow+gnd plugged into the Arduino or else I get a lot of PWM noise rendering my ESC useless.

ESC is 5V
USB is 5V

Question:

This is my due diligence to not blowing anything up. What is the safest way to plug in power from both USB and the ESC? Same voltage, difference sources. Or can I just connect the grounds and call it good?

Connecting the grounds would work.

You could also connect the 7.2V lipo to the Vin pin on the UNO. The UNO will automatically switch from USB to Vin, if it's present.


Changing timing intervals with millis() My goal is to run a vibrating motor for specific time intervals. I am using the millis() function to successfully turn the motor on and off, but only if the intervalOn = intervalOff. The problem comes when I try to change the intervals to turn the motor on for e.g. 120 ms, then turn off for 200 ms etc. My code seems to cause AVR restart and my motor sometimes stays running. First I thought this is caused by insufficient decouple capacitor (I have 100 uF one) but when running the millis() code with one no-changing interval, it all works flawlessly...
Is there any other way to change the intervals?

The Vibrating() function gets called from the loop() whenever vibrEnabled = true

unsigned long interval = 0;
unsigned long previousMillis = 0;
int last = 120;
int pause = 200;

void Vibrating()
{
unsigned long currentMillis = millis();
static byte cyclesPassed = 0;

if((unsigned long)(currentMillis - previousMillis) >= interval)
{
    PORTC ^= (1<<PC1);//toggle motor

    if(interval != last) //this part causes the problem
        interval = last; //
    else                 //
        interval = pause;//

    cyclesPassed++;
    if(cyclesPassed == 8)//motor is on 4x
    {
    cyclesPassed = 0;
    vibrEnabled = false;
    }

    previousMillis = millis();
 }
}

Maybe your vibrating motor is actually shaking something loose. A dodgy batter clip or something.
Maybe your vibrating motor is drawing too much current and power-cycling the board.
Maybe your vibrating motor is doing weird, bad things like generating back-EMF spikes that it's sending back into the arduino.

It's probably number 3. Generally speaking, you never power motors off an output pin. Run the output into a mosfet or something with a flyback diode across it. Google "circuit to power motor from digital out".


SimpleAudioPlayer + sleep function I have tested the SimpleAudioPlayer example.

https://www.arduino.cc/en/Tutorial/SimpleAudioPlayer

This works fine, but when I add a sleep(1000) at the end of the loop() function, the music sounds dismembered (second run).

void loop()
{
    // ... source from the example

    myFile.close();
    Serial.println("End of file. Thank you for listening!");

    sleep(1000);
}

Does anyone have any idea on how to resolve this?

sleep() is something different. You are probably want to use delay(1000) instead.

sleep() comes from libsam and is not very well documented for use within the Arduino environment. There is probably a conflicting timer or interrupt between sleep() and the Audio.h library. So sticking with delay() is probably your best option.


Increase PWM bit resolution on only one timer 2 output I am new here and I know that this basic question has been answered in the past but what I want to know is this. And I cant figure out how to add this to one of those threads. Sorry in advance if I am posting this wrong.

Arduino Uno

I have a motor driven PWM off output 10 and output 9 is used for the display, can I change the resolution of output 10 only to 16 bit? or will both outputs need to be used as PWM when changing timer 2 to 16 bit? All of the coding samples I see are for changing both outputs.

As long as you don't use PWM (i.e. analogWrite) on pin 9, any changes made to timer1 won't affect pin 9.

It will change both outputs, as both use the same (single) timer.

But you can use code to convert a 8-bit PWM value to a 16-bit value by simply multiplying the 8-bit value by 256.


How can I assign a variable to a function output in Arduino? I'm trying to assign the output of my function (which adjusts a DAC output) to a variable so I can print and display it in my serial monitor. Here's the code

#include <Wire.h>
#include <Adafruit_MCP4725.h>

Adafruit_MCP4725 dac;

int volza;

void setup() {
  Serial.begin(38400);
  Serial.println("Hello!");
  dac.begin(0x60);
}

void loop() {
    volza = dac.setVoltage(1095, 1); // THIS IS THE PROBLEM
    Serial.println(volza);
}

I am receiving an error because of the commented line. I think it's because I am trying to return a value while inside a void loop. How do you fix this?

The setVoltage method has the following prototype:

void setVoltage( uint16_t output, bool writeEEPROM );

This means it does not return a value.

If you expect to return 1095, why not write:

volza = 1095;
setVoltage(volza, 1);
Serial.println(volza);

Some background information:

Assume you want to have the library a getVoltage method, than this is possible (you have to make a copy in your own project of the file and add the method. However, I'm not sure how easy it is to get the value from the EEPROM. If it is not easy, there is some programming work to do. Another solution is to store the value in memory, but that means some extra bytes from the scarce free SRAM. Also, in theory the content could be changed already (if another MCU would have access to the EEPROM too).


Analog angle conversion from +70° to -70° I am using below sensor (accelerometer) .My application is a solar tracker, where I wanted to convert the sensor output into +70° to -70° format.

My question is how can I convert the angle?

#define ADC_ref 2.56
#define zero_x 1.569
#define zero_y 1.569
#define zero_z 1.569
#define sensitivity_x 0.3
#define sensitivity_y 0.3
#define sensitivity_z 0.3

unsigned int value_x;
unsigned int value_y;
unsigned int value_z;

float xv;
float yv;
float zv;

float angle_x;
float angle_y;
float angle_z;

void setup() {
  //analogReference(INTERNAL2V56);
  Serial.begin(9600);
}

void loop() {
  value_x = analogRead(A0);

//  value_y = analogRead(A1);
  //value_z = analogRead(A2);

  Serial.print("voltage  of x");
  Serial.println(value_x);
  /*Serial.print("voltage  of y");
   Serial.println(value_y);
   Serial.print("voltage  of z");
   Serial.println(value_z);
   */
  //xv=(value_x/1024.0*2.5)/sensitivity_x;
/*  zv=(value_z/1024.0*ADC_ref-zero_z)/sensitivity_z;
  yv=(value_y/1024.0*ADC_ref-zero_y)/sensitivity_y;
  xv=(0.0032226562499999998*value_x)/sensitivity_x;
  angle_x =atan2(-yv,-zv)*57.2957795+90;

  Serial.print ("x= ");
  Serial.println (xv);
  Serial.print("x_degree= ");
  Serial.print(angle_x);
  Serial.println(" deg");

  /*Serial.print(" g ");

   Serial.print ("y= ");
   Serial.print (yv);
   Serial.print(" g ");

   Serial.print ("z= ");
   Serial.print (zv);
   Serial.print(" g ");

   Serial.print("\n");

   Serial.print("Rotation ");

   Serial.print("x= ");

   angle_x =atan2(-yv,-zv)*57.2957795+180;

   Serial.print(angle_x);
   Serial.print(" deg");
   Serial.print(" ");

   Serial.print("y= ");

   angle_y =atan2(-xv,-zv)*57.2957795+180;

   Serial.print(angle_y);
   Serial.print(" deg");
   Serial.print(" ");

   Serial.print("z= ");

   angle_z =atan2(-yv,-xv)*57.2957795+180;

   Serial.print(angle_z);
   Serial.print(" deg");
   Serial.print("\n");
   */
  delay(1000);
  //delay(1000);
}

Description
Datasheet of ADXL335

I have inclinometer off the shelf its Vout is 0~5 V and angle measure from -70° to 70°, and I calculated as below.

void calcPos()
{
  Sensor_Value=analogRead(A3);
  voltage = Sensor_Value * ARDUINO_ANALOG_SCALING;
  tracker_actual_pos=(30*voltage)-75;
}

So atan2(y,x) gives the angle CCW from the x axis in radians, limited to [-pi,pi].

If you want it converted to degrees CW from the Y axis, you would do

azimuth=90.0-atan2(y,x)*57.295779;

If you need to constrain it to -70,70 then:

azimuth_constrained=constrain(azimuth,-70,70);


Arduino eeprom_put sketch writes data in two locations? Using precisely this code - the eeprom_put example in the Arduino IDE, and am seeing some strange results...

The sketch does write correctly to eeAddress = 0, and the corresponding eeprom_get sketch does return the data.

Please note that I've initialized the entire EEPROM with 'FF's before any test...

The weird part is this sketch writes exactly the same data starting at Address = 2048. The loop is not running; I see no jump to offset 2048... I gotta be missing something!

I'm dumping EEPROM using avrdude, and viewing results in an external hex editor.

How is this stuff stored? Apart from not being able to directly view a float - OK, I get it - should the other data be simply viewable in hex?

My own experiments in writing hex bytes directly also work, but also write in two locations.

Small update to this: Precisely the same behavior seen with a RobotDyn Mega. Both the 'clone' Mega and the RobotDyn report: Device signature = 0x1e9801 (probably m2560)

#include <EEPROM.h>

struct MyObject {
  float field1;
  byte field2;
  char name[10];
};

void setup() {

  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  float f = 123.456f;  //Variable to store in EEPROM.
  int eeAddress = 0;   //Location we want the data to be put.

  //One simple call, with the address first and the object second.
  EEPROM.put(eeAddress, f);

  Serial.println("Written float data type!");

  /** Put is designed for use with custom structures also. **/

  //Data to store.
  MyObject customVar = {
    3.14f,
    65,
    "Working!"
  };

  eeAddress += sizeof(float); //Move address to the next byte after float 'f'.

  EEPROM.put(eeAddress, customVar);
  Serial.print("Written custom data type! \n\nView the example sketch eeprom_get to see how you can retrieve the values!");
}

void loop() {
  /* Empty loop */
}

What is probably happening is aliasing.  Let's say your processor has a 16 bit address bus.  16 bits can count up to 2^16 = 65536 = 64k memory addresses.  Each address is a byte (B) so your processor has 64k-Bytes of address space.  It can physically address 64kB of memory.

What happens if you only have one memory chip with 4KBytes of memory, with  only 12 address lines?  Well, if the designer was lazy (or cost-conscious), the first 12 address lines on the processor will be connected to the 12 lines on the memory chip.  The other 4 lines on the processor will be ignored.

So it doesn't matter what the processor does with address lines 13-16 -- they're not connected to the memory chip.  Therefore the contents of the memory chip appears where you expect, starting at address 0, but also again at address 4096, and again at address 8192 and so on.


Safely powering a relay from same source as attiny/arduino? My project involves using ATTINY to control a 5v relay (specifically JZC-11F and will be ground triggered) in an automotive setting.

I keep seeing the warnings of powering a relay from the same source as the ATTINY (or arduino), everything I can find says you need a completely separate source.

I'm still working on a 12~v to 5v power circuit that is safe from the issues that arise from being in an automotive setting (load dumps, noisy, reverse polarity protection..etc) but saying I have that figured out and I have a clean 5v source for power, do I have to duplicate that circuit just for the relay? or are there a ways of preventing the relay from eventually shorting out the ATTINY?

Plan B:
What if I scratch the whole 5v relay and set it up to trigger an external standard 12v automotive relay (this is probably more ideal)? Is the ATTINY capable of triggering a 12v relay via ground? if not what are the recommended ways of making this happen?

side note: I'm know code I don't know EE but I'm trying. The end goal is to combine everything onto a custom pcb, so any suggestions about the 12v-5 using an off the shelf car usb adapter or a premade board are unnecessary (seems to be the go-to answer on that subject). I have a separate post regarding that circuit so if at all possible please stick to the relay questions.

do I have to duplicate that circuit just for the relay?

No, not really, no.

  Is the ATTINY capable of triggering a 12v relay via ground?

The ATTtiny is capable of triggering a transistor - the transistor is capable of triggering a 12V relay.

Unless your relay is incredibly high powered and the coil takes (and generates through back-EMF) massive amounts of current, there really is no problem running it alongside a small microcontroller. Just be sure you have the flyback diode, and maybe a damping capacitor as well to absorb noise.

TBH you're probably going to be getting more noise from contact spark than you are from the relay's coil.


Communication arduino MODBUS fails on high number of registers When I try to run the following program it runs ok:

#include <modbus.h>
#include <modbusDevice.h>
#include <modbusRegBank.h>
#include <modbusSlave.h>
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
modbusDevice regBank;
modbusSlave slave;

void setup()
{
  lcd.begin(40, 2);
  regBank.setId(10);
  int numSet=0;
  for (int i=0; i <= 300; i++){
    if (numSet <= 8) {
      regBank.add(i);
    }
    if (numSet == 16) {
      numSet = 0;
    }
    numSet++;
  }
  slave._device = &regBank;
  slave.setBaud(9600);
}

void loop() {
  int numSet=0;
  for (int i=0; i <= 300; i++){
    if (numSet <= 8) {
        if (regBank.get(i) >= 1) {
          lcd.setCursor(2, 0);
          lcd.print("test");
        }
    }
    if (numSet == 16) {
      numSet = 0;
    }
    numSet++;
  }
  slave.run();
}

But whenever I add more code, or raise the number of the loops, it starts failing to communicate over MODBUS.

Is it that some part of the Arduino can't handle the amount of work? It's confusing because it not only fails when adding more regBank.add() or regBank.get() actions, but also when adding more program code (for example add 40 lines of code to write to the LCD display).

Before you decided to switch platforms, take the time to figure out what your resource usage is. After compiling you'll get a report of the amount of memory you're consuming, check that first.

After that, it would be helpful if you could describe more clearly what you're seeing when the code fails.


Do Arduinos meet military standards? Do Arduinos meet military standards?

If not, where does it fall short? Is it something internal to the chip which might be corrected via external circuit? How could I evaluate the potential of a device I'm building?

It depends on the application. For something like a rechargeable torch, Arduino might exceed the specifications. For a weapons system, NEVER (and this is one of the specific prohibitions in the license agreement - see section 1.5 note: link currently broken). You also have to consider that there's literally thousands of armies in the world and they all have different standards. What might be acceptable to one might not be acceptable to another. Hamas uses rockets I wouldn't consider safe for anything, and they use them effectively - the Qassam rocket would never meet US military standards but it works great for Hamas.

US military standards are so complicated, nobody can answer this question for you. You're gonna need an army of lawyers to do that... here's a link to some documents to get started though...

Please note there are multiple standards which may apply to a given device. For example, you will see common off the shelf desktop computers (running Windows) used for some things in a military installation, but they could never be used to control a vehicle. Bottom line - you're gonna need a lawyer to navigate this. (You are better off selling your devices directly to soldiers, if you can live with that if it fails.)

http://www.dsp.dla.mil/ - Terrible site - get used to that if you want to deal with govs.

OH BTW... if you want to use Arduino to prototype something, and you plan to remove "Arduino" later, running straight from the ATMega - that's the whole point of Arduino! It is a prototyping system, not intended to be used wholly in products. Arduino is very little more than a break-out board for the ATMega processor, a robust (kinda) power supply, and a runtime environment in C++.


Object Array using Inheritance I would like to create an array of a generic type so I can use multiple sensors and make my code as extensible as possible.

/*
  Planning for good design. Agent library
  should be able to use more than one sensor.

  The agent's constructor will accept a vector
  of sensors.
*/
class Sensor
{
 public:
  Sensor(){};
};

My implementation class

#include "Arduino.h"

class UltraSonicSensor: public Sensor {
 public:
  /*
    Constructors
   */
  UltraSonicSensor(){};
  UltraSonicSensor(int pin){
    pin_ = pin;
  };
  int Sense(){ return 20;};
  /*
    Measure Distance
   */
  float DistanceMeasure(void);
 private:
  /*
    Class only suppports Metric
   */
  float microseconds_to_centimeters(void);
  int pin_;
  long duration_;
};

#endif // SROBOT_SENSORS_ULTRASONIC_H_

I have tried many, many variations of this code but always the same error

Sensor *sensors[2];

UltraSonicSensor uSensor;
sensors[0] = &uSensor;

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

void loop(){
  Serial.println("starting...");
  delay(1000);
  Serial.println("ok");
//  delay(2000);
//  for (int i = 0; i < sensors.size(); i++) {
////    sensors[i].Sense();
//  }
}

The error is always a variation of

main:10: error: 'sensors' does not name a type
 sensors[0] = &uSensor;
 ^
exit status 1
'sensors' does not name a type

I also used the code for a small replacement vector class but also the same error

You have to do it inside of function:

Sensor *sensors[2];

UltraSonicSensor uSensor;

void setup(){
  Serial.begin(9600);
  sensors[0] = &uSensor;
}

Or directly:

UltraSonicSensor uSensor;

Sensor *sensors[] = {&uSensor};

Don't forget to make method Sense() virtual in the base class and in the inherited classes. Otherwise you'll have to also find out the type of the object and typecast it to correct class pointer before it's use.

class Sensor
{
  public:
    virtual int Sense() = 0; // pure virtual base class
};

// and inherited class:

class UltraSonicSensor: public Sensor {
  public:
    // ...

    // Prototype must be exactly the same, by using override
    // is ensured it actually overrides something from the parent class.
    virtual int Sense() override {
        // ...
    }
    // ...
}

Also the last versions of Arduino IDE supports C++11 standard so you can use range based for loop:

for (Sensor * sensor : sensors) {
    int val = sensor->Sense();
    // ...
}


Reading Ground/Open signal wire combonations to power specific LED's - Can it be done? This might be a super easy question to answer. I ordered an Arduino Uno anyways for the sole purpose to understand this. Would not mind getting a jump on things before it's here.

I would like to setup the Arduino Uno to be used as a gear indicator for GM transmissions (specifically right now the GM 4l60e). Below is how it currently tells the computer/cluster what gear it's in.

This uses a range switch. Basically it's a combination of 4 wires that are grounded (low) in a specific order, the computer reads it, and displays what gear the transmission is in. There are 4 signal wires - Signal A,B,C, and P. Below is how the range switch signals it:

Park    - A=low,  B=open, C=open, P=low
Reverse - A=low,  B=low,  C=open, P=open
Neutral - A=open, B=low,  C=open, P=low
OverDrv - A=open, B=low,  C=low,  P=open
Drive 3 - A=low,  B=low,  C=low,  P=low
Drive 2 - A=low,  B=open, C=low,  P=open
Drive 1 - A=open, B=open, C=low,  P=low

I am wondering what would be the best way to go about this? The Arduino would be powered on by ignition. Display would be an LED (9-12V) output from the Arduino to each gear on a floor mount shifter. Total of 7 LEDs.

Hopefully this is easy to understand what I am trying to do. Thanks!

First of all, Arduino is a 5V device, as such to drive the 9-12V LED you will need to use one or more transistors (depending on the LEDs type, number and connection, in series or in parallel).

Also, powering the Arduino from a 9-12V is not the best option: Arduino Uno has an onboard voltage regulator, but goes up to 9V maximum and, unless you go for the original one or a reputable manufacturer (Arduino is an open source project) I wouldn't go above 6V, because non-reputable manufacturers tend to use lower specs devices, like regulators which can get too hot when powered with high voltage: consider that the regulator will have to dissipate any excess energy into heat.

Said that, and knowing nothing more than what you said about the transmission you are describing, I assume the status open stands for open collector, meaning that it is not going to draw any current, so the following circuit is what you should use:

simulate this circuit – Schematic created using CircuitLab

The diagram assumes you are using digital pins 5 to 8 of your Arduino in INPUT mode and the Arduino GND is at the same voltage level as the transmission: this might be a big assumption, depending on how you power your Arduino (not from a battery pack, to be clear).

When node A is in open state, the voltage on Arduino pin 5 will be 5V, or HIGH as Arduino reports it. When node A is in low state then the voltage on Arduino pin 5 will be 0V, or LOW in Arduino lingo.

Resistors from R1 to R4 are there to limit current drawn when the gearbox is in state low.

UPDATE: I'm assuming the gearbox shares the same ground and operates at 5V,a s the Arduino does. If that's not he case and the gearbox operates at an higher voltage or does not share the same ground, the circuit will not work and you risk damaging the Arduino and/or the gearbox.

You can find a simulation of the above circuit where you can play with the different pins here.

The same occurs for the other pins, so your code will have to scan the 4 pins for their state and update your display accordingly, like:

#define PIN_A 5
#define PIN_B 6
#define PIN_C 7
#define PIN_P 8

void setup() {
  pinMode(PIN_A, INPUT);
  pinMode(PIN_B, INPUT);
  pinMode(PIN_C, INPUT);
  pinMode(PIN_P, INPUT);
}

#define PARK 0;
#define DRIVE_1 1;
#define DRIVE_2 2;
#define DRIVE_3 3;
#define OVER_DRIVE 4;
#define REVERSE 5;
#define NEUTRAL 99;
#define UNDEFINED 255;

unsigned int gear = UNDEFINED;
void loop() {
    bool A = digitalRead(PIN_A);
    bool B = digitalRead(PIN_B);
    bool C = digitalRead(PIN_C);
    bool P = digitalRead(PIN_P);

    if (!A && B && C && !P) {
      // Park - A=low, B=open, C=open, P=low
      gear = PARK;
    } else if (!A && !B && C && P) {
      // Reverse - A=low, B=low, C=open, P=open
      gear = REVERSE;
    } else if (A && !B && C && !P) {
      // Neutral - A=open, B=low, C=open, P=low
      gear = NEUTRAL;
    } else if (A && !B && !C && P) {
      // OverDrv - A=open, B=low, C=low, P=open
      gear = OVER_DRIVE;
    } else if (!A && !B && !C && !P) {
      // Drive 3 - A=low, B=low, C=low, P=low
      gear = DRIVE_3;
    } else if (!A && B && !C && P) {
      // Drive 2 - A=low, B=open, C=low, P=open
      gear = DRIVE_2;
    } else if (A && B && !C && !P) {
      // Drive 1 - A=open, B=open, C=low, P=low
      gear = DRIVE_1;
    } else {
      // none of the above
      gear = UNDEFINED;
    }
    // update your display here
}

Please note the above code is NOT the most efficient, but I believe it's easier to read and understand than a version using bitwise operations to identify the possible combinations.


difference between the nano and the nano every So I wondered what the difference between the nano and the nano every is and why the nano every is so much cheaper than the nano.

I'm new to the microcontroller business and I would like to know what would be better for what situation.

The classic Nano has ATmega 328p MCU, same as Uno. The 328p is classic AVR ATmega as used in Arduinos from the start and before in many AVR MCU projects for over 20 years now. There is large knowlege base for this MCUs, many ready codes in form of libraries, snippets, tutorials.

The Nano Every and Uno WiFi Rev 2 use a modern version of the AVR based MCU a so called megaAVR_0-series, an ATmega4809. It uses the same AVR CPU architecture in core of the MCU so the compiler is the same as for 328p and co., but the MCU peripherals configuration is very different then in the classic ATmegas. So the old knowledge base about AVR MCU peripherals doesn't help here.

The lower price is not related to manufacturing costs. The possible reasons are:

better price by MCU manufacturer at introduction of the new MCU family to market
higher price of classic Nano because it is popular and together with classic Uno founds Arduino as company
getting the new chip to Arduino power users to build up the knowledge and code base for the new MCU

To mention some more differences of classic Nano and Nano Every: Nano uses a bootloader for sketch upload and an external USB chip for USB communication. Nano Every doesn't use a bootloader, it has an on board UPDI programmer in form of a small SAMD MCU which serves as USB adapter for serial communication too.


How to change the baud rate of ESP8266 (12E) using an Arduino Uno? I have with me an Arduino UNO and an ESP8266 (12E) WiFi Module. I need to make a webserver using the two. I read that the default baud rate for ESP8266 is 115200, and that the software serial pins can't handle such high speeds. I dont have an USB-UART converter at hand. Is there a way to use my Arduino as one to change the baud rate, so that I can interface with the chip using the software serial pins of the Arduino later.

You can use this block of code in Arduino to set baud rate...

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

void loop() {}

Change value in serial.begin() as per your value.


How to use a precompiled library in a project with Arduino-IDE I'm discovering the Arduino development and after quite some googling, I can't find an answer to the following question.

I'd like to distribute some code as mylib.h + precompiled mylib.o (this will be code ported from sources which I can't divulgate).
How is it possible to build a sketch using this precompiled mylib.o in the Arduino-IDE environment?
Do I simply have to put this mylib.o in a specific path and include the mylib.h in the sketch? If yes, which path? If no, what specific configuration steps do I have to follow?

Thanks in advance.

See https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification

  library.properties file format
  [...]
  precompiled - (available from Arduino IDE 1.8.6/arduino-builder 1.4.0) (optional) set to true to allow the use of .a (archive) and .so (shared object) files. The .a/.so file must be located at src/{build.mcu} where {build.mcu} is the architecture name of the target the file was compiled for. Ex: cortex-m3 for the Arduino DUE. The static library should be linked as an ldflag.

So with the correct metadata and file layout the precompiled objects should be available.
You'll need to set the architectures property to indicate you're using esp8266 as your tag suggests.

More info on the library manager here https://github.com/arduino/Arduino/wiki/Library-Manager-FAQ including how to add to the public library list.


Using RFID and fingerprint sensor together I am using both an RFID and a fingerprint sensor in my project. When running the program, the RFID is detected but the fingerprint sensor is not detected and hence my code is not going forward.

Here is my code

#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
#include <MFRC522.h>
#include <SPI.h>

#define SAD 10
#define RST 5
MFRC522 nfc(SAD, RST);

uint8_t id;
uint8_t getFingerprintEnroll();
int getFingerprintIDez();

// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino  (WHITE wire)
SoftwareSerial mySerial(2, 3);
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

void setup() {
   SPI.begin();
   Serial.begin(115200);
    Serial.println("Looking for MFRC522.");
   nfc.begin();
   byte version = nfc.getFirmwareVersion();
  if (! version) {
    Serial.print("Didn't find MFRC522 board.");
    while (1); //halt
  }

  Serial.print("Found chip MFRC522 ");
  Serial.print("Firmware ver. 0x");
  Serial.print(version, HEX);
  Serial.println(".");
  Serial.begin(9600);

  Serial.println("Fingerprint and RFID Test");

  finger.begin(57600);
  if (finger.verifyPassword()) {
   Serial.println("Found fingerprint sensor!");
  } else {
    Serial.println("Did not find fingerprint sensor :(");
    while (1);
  }
}

char abc;
void loop() {
    abc = Serial.read();
    switch (abc) {
      case '1': {
             //Enroll method
      }
      break ;
      case '2': {
        //verify method
      }break;
      case '3': {
       //rfid method
      }
   }
}

Get rid of the Serial.begin(9600). You're accidentally changing the Serial baud rate without doing the same in the serial monitor so you'll probably see gibberish, if anything.


ESP8266 cannot create TCP connections to this particular server EDIT: I have created an issue about this here: https://github.com/esp8266/Arduino/issues/4593

I have this server: 185.205.210.197
(Check that it works: http://185.205.210.197/)

And I have this code in my ESP8266:

#include <ESP8266WiFi.h>

#define HOST "185.205.210.197"
#define PORT 80
#define WIFI_SSID "SSID"
#define WIFI_PSW "PASSWORD"

const char* ssid = WIFI_SSID;
const char* password = WIFI_PSW;

void setup () {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(5000);
    Serial.println("Connecting to Wifi...");
  }

  while(!pingServer()) {
    delay(3000); //Send a request every 3 seconds
  }
}

void loop() {}

bool pingServer() {
  WiFiClient client;

  if (!client.connect(HOST, PORT)) {
    Serial.println("connection failed");
    return false;
  }

  Serial.println("connection success!");
  return true;
}

The expected result: Connection success, but got connection failed.

If I try connecting with my PC, it works, only with ESP8266 it doesn't.

Tapping with Wireshark I suspect that there is a problem with ESP8266 TCP packets, here I leave them for you to analyze:

PC TCP connection request (which works):

000030006b081c001a48ea4c0000000010009e098004dba400000000800401009e090b221f000000c603000004000000880254009801a7ad45b7000af5f4e90c000af5f4e90c603c0000aaaa0300000008004500003c000040003706cb37b9cdd2c5c0a82b490050df312dfea1498c6ac92aa0120000079c00000204058c0402080a336f35554aeb0fe90103030700ead7d1

ESP8266 TCP connection request (which receives no response from server):

000019006f080000952a9f520000000012049e098004daa1000801a200000af5f4e90c2c3ae80f137f000af5f4e90c5000aaaa0300000008004500002c00030000ff06431dc0a82b70b9cdd2c5c00100500000196d000000006002086040f80000020402189ccdd933

What I've also checked:

The ESP connects fine to other servers.
There is no firewall blocking the connection between ESP and the server.
I've tried this in different networks and conditions, the error persists.
Other computers can connect to the server, so ESP should be able as well.
Tried with different ESP8266 boards to rule out hardware malfunctioning.
I am using NODEMCU V0.9 board (original firmware) with Arduino IDE and this ESP8266 library.

How to replicate:

Using the latest Arduino IDE and ESP8266 library.
Check that the test server works at http://185.205.210.197:80/ (just open this link basically and see that is running nginx).
Copy and upload the code above to your ESP8266 (NODEMCU or similar).
Open the Arduino IDE console/monitor and confirm that no connection is established to port 80.
Rage in admiration for such a strange bug.

I've opened an Issue for this: https://github.com/esp8266/Arduino/issues/4593

Not a cookie cutter answer, I did a quick test and my ESP8266 does connect to you nginx. Of course you do not accept the params from my fridge, but this is what I see in the log.

7007 :
7010 :

For online documentation and support please refer to
7012 : nginx.org.

7015 : Commercial support is available at
7018 : nginx.com.

7020 :
7022 :

Thank you for using nginx.

7024 :
7026 :
7028 : HTTP : closing connection

You should be able to see that on your side as well.

I am using letscontrolit/ESPEASY  https://github.com/letscontrolit/ESPEasy

And their code to connect looks like

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  if (!ControllerSettings.connectToHost(client))
  {
    connectionFailures++;
    addLog(LOG_LEVEL_ERROR, F("HTTP : connection failed"));
    return false;
}

  boolean connectToHost(WiFiClient &client) {
    if (!checkHostReachable(true)) {
      return false; // Host not reachable
    }
    byte retry = 2;
    bool connected = false;
    while (retry > 0 && !connected) {
      --retry;
      connected = client.connect(getIP(), Port);
      if (connected) return true;
      if (!checkHostReachable(false))
        return false;
    }
    return false;
}

I am using generic HTTP for my controller which here: https://github.com/letscontrolit/ESPEasy/blob/503fd3555e010b08b48fb2dc18290ef120005308/src/_C008.ino

You could try the connect to function to see if that works for you.


Arduino water pump not working and beeping I’m new to Arduino and am trying to build a plant watering system without much knowledge on the subject. But my water pump is not working as I expected it to.

I wanted to keep it simple so I bought a Arduino Motor Shield for my Arduino Uno R3. I’m using a motor rated at 3-9V (motor is shown below), I’ve tried two different DC adaptors plugged into the power supply port on the arduino, 12V 1.5A and 12V 2A, even though the motor is rated at 9V, I’ve read that I need a 12V adapter to power the motor shield.
http://www.mabuchi-motor.co.jp/cgi-bin/catalog/e_catalog.cgi?CAT_ID=rs_360sh

The first problem is If I run the motor at full speed, analogWrite(3, 255), it sounds like its going to explode, so I’m trying to run it at a lower speed. But If use values anywhere below 170 the motor will not run and will only make a beeping sound.

Secondly, regardless of the PWM value I run the motor at, the chip gets very hot very quickly.

My question is, why can’t I run the pump at lower PWM values, and why is it getting so hot?
If I bought a 12V water pump and used the same setup, would I not have any of these problems?

EDIT:
an update...
it seems to basically work now. i have a feeling it wasn't working great because I was previously using a powerbar

It will run on max power PWM(255) for about a minute, and then stop working, which is okay. It will stop and then the motor shield lights will start blinking. Does anybody have any guesses what is happening? The motorshield chip is a little hot, so overheating is a possibility. Or is there not enough current ?

video
https://www.youtube.com/watch?v=xdxf3f_Svqs

void setup() {

//  //Setup Channel A
  pinMode(12, OUTPUT); //Initiates Motor Channel A pin
  pinMode(9, OUTPUT); //Initiates Brake Channel A pin
}

void loop(){
  //forward @ full speed, A
  digitalWrite(12, HIGH); //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 170);   //Spins the motor on Channel A at a speed. approx 90 is min

  delay(3000);

  digitalWrite(9, HIGH); //Engage the Brake for Channel A

  delay(1000);

}

Regarding your motor just making high pitched noise (beeping) I would say that you are not supplying enough power to your motor for it to pull in the load and get rotating, you might try to first get it started by a higher power setting (PWM) and then when it's running see how far down you can set it before it stalls (stops).

I don't belive a 12V pump would work any different.

As to the motor and L298 chip getting hot, this is sort of normal and in some cases would require som way of dissipating this heat. A heatsink might be an option.

If you were to overheat the L298 it will shut down before being destroyed (it should).


How can you determine the duration of a timer interrupt? So I understand that when setting a timer interrupt you don't use nanoseconds or milliseconds, but the actual number of clock cycles. However, I don't understand how you would be able to setup a specific time this way. If I wanted my interrupt to go off every 20 milliseconds would I have to divide that by the duration of each clock cycle?

The timer takes its time from the system clock. That may be, typically, 16MHz. We call this F_clk_io for the Frequency of the IO CLocK.

Every time that clock ticks the timer counts. Or, depending on settings, every time that clock ticks the prescaler counts, and eventually the output of the prescaler ticks and then the timer counts.

So first you need to divide the F_clk_io by the prescaler. That may be 1:1, 1:2, 1:4, 1:8, etc, depending on settings. No prescaler is the same as a prescaler of 1:1.

So say you have selected a 1:4 prescaler.  The timer's frequency is then F_clk_io / 4, or if it's 16MHz you're running at, then the timer's frequency is 16/4 = 4MHz.

So at 4MHz each tick lasts for 1/4000000 = 250ns.

If you want 20ms you need to know how many ticks that would be.

20ms in nanoseconds would be 20000000. 20000000 / 250 = 80000 ticks.

Now, there's a problem there. 80000 won't fit into the 16-bit registers of a 16-bit timer. The maximum you can have is 65535. So we're going to need to slow things down a bit.

Set the prescaler to 1:8 and see what happens...

16/8 = 2MHz. 1/2000000 = 500ns. 20000000 / 500 = 40000 ticks.

That fits.  See how doubling the prescaler has simply halved the number of ticks you get in the same time?

So setting it to a prescaler of 1:8 and letting it tick 40000 times should give you 20ms.

Except it doesn't.

It gives you 20.0005ms.

Why? Because the interrupt triggers and the counter resets when it reaches the target count, not when it passes the target count.  And since it starts counting at 0, there's actually 40001 ticks there. So you have to subtract 1 from the number of ticks.

So the finished formula is:

ticks = ((F_clk_io ÷ Prescale) × time) - 1

Things get more tricky when you are working with a smaller chip though and only have an 8-bit timer to use. With that the maximum ticks you can have is a mere 255. So you will have to use a much bigger prescale to get it to fit in. If that's even possible.  If it's not, then there are other tricks you can use.  My favourite is a manual pre-scale:

Run the timer at a multiple of your target frequency (10x is easy)
Count the number of times the interrupt triggers
When the interrupt has triggered 10 times (if using a 10x faster timer) then reset the count to 0 and trigger your real ISR code.

10x is simple to program and visualize, but it's not very programatically efficient. Better is to use a "power of two" multiple since you can examine a single bit in your counter to see if it's reached the target count.  Only minimal differences though, and not really worth worrying about unless you are having a very fast timer interrupt.


How to identify connection lost on HC-06? I am making an RC car on Arduino Uno. I have connected an L298N motor driver to an Arduino Uno to control 2 DC motors. I also connected an HC-06 to the Uno to receive commands from an Android smartphone. Everything is working fine. But if a connection is lost (because of low battery or disconnected on Android application), when the RC car is moving it is not stopping. It stops only when there is connection and "s"(stop) command is received via Bluetooth.

int in1 = 4;
int in2 = 5;
int in3 = 6;
int in4 = 7;

void setup() {
  Serial.begin(9600);
  pinMode (in1, OUTPUT);
  pinMode (in2, OUTPUT);
  pinMode (in3, OUTPUT);
  pinMode (in4, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    int command = Serial.read();
    move(command);
  }
}

void move(int command) {
    if (command == 'f') forward();
    else if (command == 'b') backward();
    else if (command == 'l') left();
    else if (command == 'L') leftback();
    else if (command == 'r') right();
    else if (command == 'R') rightback();
    else if (command == 's') stop();
}

Now what I want is to identify whether there is connection or it is lost. For example:

if(Serial.connectionLost()) stop();

Is there such a function to identify the connection state? If not, is it possible to implement this function in another way?

My first one or couple of HC-06es brought its LED signal out to a pin on the base board, labeled "STATE" on mine. I tested the LED state on every loop and if it was changing regularly, took that to indicate whether it was waiting for a connection.

Later modules no longer bring out the LED signal but it is available on module's edge-pin 24, according to a (now 6yo) datasheet.

By cutting the plastic sleeve and bringing out the signal to the baseboard again, you use it to monitor the connection.


Problems integrating Reed Switch and Solenoid Lock in Arduino Code I am trying to integrate solenoid lock, reed switch in my Arduino Code. The flow that I am trying to achieve is - first, the solenoid lock is set to LOW and then the program checks if reed switch is High or Low. Only if its High I want to proceed further. However, even when the reed switch is HIGH the program is not executing further. Here is my code below:

    #include<HX711_ADC.h>
    #include<math.h>

    //pins for lock
    int solenoidPin = 7;

    //pins for reed switch
    int reedSwitch = 2;
    bool reedSwitchStatus;

    //pin for led
    int led_pin= 9;

    void setup()
    {
      Serial.begin(38400);
      pinMode(solenoidPin, OUTPUT);
      pinMode(reedSwitch, INPUT);

      doorUnlock();
    }

    void loop()
      {}

    void doorUnlock()
    {
      digitalWrite(solenoidPin, LOW);
      delay(5000);
      checkReedSwitchStatus();
    }

    void checkReedSwitchStatus()
    {
      reedSwitchStatus = digitalRead(reedSwitch);

      if(reedSwitchStatus == 1)
      {
        Serial.println("Beginning Transaction");
        beginTransaction();
        }
      if (reedSwitchStatus == 0)
        {
          Serial.println("Ending trasaction");
          endTransaction();
          }
      }
      void beginTransaction()
      {
      digitalWrite(led_pin, HIGH);
      delay(500);
      digitalWrite(led_pin, LOW);
      delay(500);
      }

My issue is the beginTransaction function is never executed. Serial monitor continuously prints 'Beginning Transaction'. Attached the screenshot of the serial monitor. Please suggest me what is the error in my code. Thanks in advance!

The problem is, that you don't initiate the LED's pin to an output. On reset the pin is configured as input. Doing a digitalWrite(led_pin, HIGH) in this state just enables the internal pullup resistor. If you measure the voltage without the LED connected, it will be 5V, but since the pin only provides a very small amount of current through the pullup resistor, the LED cannot light up when connected.

You need to configure the LED's pin as an output through

pinMode(led_pin, OUTPUT);

in your setup() function.

So actually the beginTransaction() function was correctly executed. You just couldn't see it.


How to use a potentiometer to access data within a 2 dimensional array? I'm trying to create a 2D array of notes that are split into 3 scales. There are 3 notes in each scale. There are 3 buttons to play each note and I want to use an available potentiometer to select each of the scales to be played.

Despite my searching I cannot understand how to achieve this correctly. So far this is what I have.

Using an Arduino Uno:

// musical notes
int C = 1046;
int D = 1175;
int E = 1319;
int F = 1397;
int G = 1598;
int A = 1760;
int B = 1976;
int C1 = 2093;
int D1 = 2349;

const int numScales = 3;
const int numNotesPerScale = 3;

const int  notes[numScales][numNotesPerScale] = {
  {C, D, E},
  {F, G, A},
  {B, C1, D1}
};

const int numberOfButtons = 3;
int buttonPin[numberOfButtons] = {2, 7, 4};
//int notes[numberOfButtons] = {C, D, E};
int ledPin[numberOfButtons] = {11, 10, 9};

int buttonState = 0;         // variable for reading the pushbutton status
int speaker = 3;                 // name of the speaker key

void setup() {

  for (int i = 0; i < numberOfButtons; i++) {
    pinMode(buttonPin[i], INPUT);
    pinMode(ledPin[i], OUTPUT);
  }
  pinMode(speaker, OUTPUT);     // set speaker to be an output
}

void loop() {
  int numScales = map(analogRead(A2), 0, 1023, 0, 2);
  //int numScales = analogRead(A2 / 341);

  for (int i = 0; i < numberOfButtons; i++) {
    checkButton(buttonPin[i], notes[i], ledPin[i]);
  }
}

void checkButton(int buttonPin, int note, int ledPin)
{
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == HIGH){
    digitalWrite(ledPin, HIGH);
    tone(speaker, note);                 // play the note
    delay(100);                       // wait for 1/10th of a second
  }  } else {
    digitalWrite(ledPin, LOW);
    noTone(speaker);                  // stop playing the note
  }
}

Using the Arduino map() function seems a reasonable approach to this, however you have a problem with the indexing.

if (numScales == 3); {

Is probably not what you want, as that condition can never be true since you set it to something in the range of 0-2 before you reach this check.

Considering only the relevant dimension, you a 3-element array, which will have legal elements numbers 0, 1, and 2

You call map(analogRead(A2), 0, 1023, 0, 2); which can produce an output in the range of 0-2, so far so good.

But then check for a value 3 which is not only illegal as in index to a 3-element array, but unable to be produced by your code.

Additionally you should probably stop trying to use the numScales variable to do double duty holding both the initial size and later also the current index.  And you should probably pass that as an argument, rather than make it a global variable.

You are also failing to ever use the current scale as an index into the notes array.  The syntax of double array indexing would be notes[x][y] but of course this should only be done with indicies to elements that exist.

It would probably also be a good idea to add some debug output of the internal logic, for example print both the raw ADC reading and the result of mapping that to the selected "scale".


Speed Control L298 motors Proceeding is the relevant part of the code for the problem I'm asking assistance with.  I'm attempting to vary the speed of the robots motors with PWM. The left motor speed can be varied numerical. The right motor fails to move. Any ideas is appreciated. The motor speed code is at the end of the sketch.
Any assistance is greatly appreciated.

//Below are the symbolic constants. Instead of having to type in a non-sensical pin number each time we want to do something we can write an easy to understand name which represents the pin, the compiler will then replace the names with the numbers
 #define LeftMotorForward 8
 #define LeftMotorBackward 9
 #define LeftMotorSpeed 10
 #define RightMotorForward 6
 #define RightMotorBackward 7
 #define RightMotorSpeed 5
 #define USTrigger 3
 #define USEcho 2
 #define MaxDistance 100
 #define LED 13

//Here we have created two 'objects', one for the servo and one for the ultrasonic sensor
 Servo servo;
 NewPing sonar(USTrigger, USEcho, MaxDistance);

//Below we are creating unsigned integer variables which we will use later on in the code. They are unsigned as they will only have postive values
 unsigned int duration;
 unsigned int distance;
 unsigned int FrontDistance;
 unsigned int LeftDistance;
 unsigned int RightDistance;
 unsigned int Time;
 unsigned int CollisionCounter;

 void setup()                                            //This block happens once on startup
 {
  Serial.begin(9600);                              //I have included the serial initialize but commented it out, if you want to debug and print information to the serial monitor just uncomment

  //Here we are setting the pin modes. As we will sending out signals from the pins we set them as outputs
  pinMode(LeftMotorForward, OUTPUT);
  pinMode(LeftMotorBackward, OUTPUT);
  pinMode(LeftMotorSpeed, OUTPUT);
  pinMode(RightMotorForward, OUTPUT);
  pinMode(RightMotorBackward, OUTPUT);
  pinMode(RightMotorSpeed, OUTPUT);
  pinMode(LED, OUTPUT);
  servo.attach(11);                                    //The servo is attached to pin 4
 }

 void loop()                                           //This block repeats itself while the Arduino is turned on
 {
  servo.write(90);                                    //Rotate the servo to face the front
  scan();                                             //Go to the scan function
  FrontDistance = distance;                           //Set the variable FrontDistance to the value of the distance returned from the scan function
  Serial.println("Front distance = ");
  Serial.print(distance);
  if(FrontDistance > 40 || FrontDistance == 0)        //If there is nothing infront of the robot within 40cm or the distance value is 0 (which for the newping libary means no ping was returned) then...
  {
   moveForward();                                     //Go to the moveForward function
  }
  else                                                //Else (if there is something infront of the robot within 40cm) then...
  {
    CollisionCounter = CollisionCounter + 1;
    moveStop();                                       //Go to the moveStop function
    navigate();
  }
 }

 void moveForward()                                    //This function tells the robot to go forward
 {

  Serial.println("");
  Serial.println("Moving forward");
  //Turn on left motor
  digitalWrite (LeftMotorBackward, LOW);
  digitalWrite(LeftMotorForward, HIGH);
  //set speed
  analogWrite(LeftMotorSpeed, 100);

 // turn on right motor
  digitalWrite(RightMotorBackward, LOW);
  digitalWrite(RightMotorForward, HIGH);
// set speed
   analogWrite (RightMotorSpeed, 75);

You are not sending a speed command to the motor, you are sending it an analog voltage with the analogWrite. If that voltage is too low, the motor will stall. A higher value should make it spin faster. If you want the speed to be more tightly controlled, you will need encoders on the motors to sense how fast they are spinning, or use stepper motors.


Arduino reduces the laser power Its important to mention that I'm noob.
I bought 500mw 405nm TTL module laser(5-12 volt) driver circuit. When I supplied laser with 12 volt, it turns on with max power. but when i connects laser TTL module to arduino (pin 11) in order to control turning on & off of laser through GRBL(CNC machine language) command with full power, the output of laser reduces.

"M05 S0" turns off the laser while
"M03 S255" should turns on the laser with full power as it is turning on with direct 12 volt supply, but its not happening.

so how can I make laser turn on with full power with arduino control?

Laser I,m using
https://www.amazon.in/gp/product/B071J2W7V8/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1

Laser driver circuit

The first thing I would recommend is to log into your Amazon account and contact the seller. Ask them to send you product documentation.

If the seller is not able to provide any, then you could return the product for a refund or try to figure it out how it works.

According to this document: TTL Laser

TTL modulators emit 100% of their power when a TTL "0" (0 VDC) is input and less than 5% of their power when a TTL "1" (5 VDC) is input.

gre_gor's comment about trying a simple PWM sketch sounds like an excellent place to start.


Wireless Sensor communication with 100Hz rate I'm doing my project on haptic feedback systems. I need a 56bits of data transmitted over wirelessly to a computer to process and send the output to another arduino. I tried ESP8266 using TCP/IP protocol. But it is very slow. Are there any faster modules to do the above task with 100hz speed?

Make one static tcp connection with a regular check and on error event to restore it in case it drops. Tcp must be able to run data at your rate.
If not, maybe the main arduino loop has delays in it.


Arduino changing output based on wire voltage I’m new to arduino and I want to build myself smart switch that can be turned of both manualy and via wifi, is there any way to change position of relay based on if another wire is live or not? Im from europe so we have 230V  outlets.
Thanks for the answer.

Maybe a wire coil wound around the wire could pick up the frequency. Though I won't write about this, since I don't know much about how you would measure this, and because I think, that you are looking the wrong way.
You want to switch one device with multiple switches (how these switches are operates is not important for now). You can look at how this is normally done in eletrical installations. Here the switches are all connected to your breaker box. And there is one component, that waits for trigger signals from the switches and will switch the target device (the light in this case) accordingly. So in the end there is only one place, where the light is switched: in the breaker box. The switches in the room are only triggers. The current for the light does not flow through them. Also they don't necessarily need to carry mains voltage (triggers could also be low voltage) (though it seems they are in fact just using mains voltage, for which I don't know the reason. Maybe to avoid additional voltage conversion).
So I propose the following solution: The mains wires (230V) are only connected to the light and a (suitable) relay board. The relay board is connected to the Arduino, which can act as a Smart Switch (switching via WiFi, time based or whatever). For manual switching you can connect a switch or button to the Arduino and program the Arduino to read it and control the relay accordingly.
This solution is way easier, than trying to sense the live voltage on the lines, and this will most likely make it more reliable . It comes down to controlling an relay board and reading a button/switch, both things with tons of tutorials on the web
Note: Since mains voltage is always really dangerous, you should be really really caution. Don't use mains voltage, when developing your device. A simple LED with current limiting resistir connected to the power line of the Arduino through the relay is sufficient to check the complete functionality. Only connect mains voltage, if you are really really sure, that you did everything correct


Can the Mouse library scroll horizontally? I'm using the Mouse library with an ATmega32U4 connected to Linux via USB.

I would like to issue horizontal scroll commands, but the Mouse.move() function only seems to accept X movement, Y movement and vertical scroll parameters.

How can I send horizontal scroll commands from the Arduino to the computer?

As suggested in the comments, I edited the core libraries to achieve this.

I'm using PlatformIO, so the library files I needed to edit were here:

~/.platformio/packages/framework-arduinoavr/libraries/Mouse/src/

And the required changes (to change a wheel parameter for horizontal (h) and vertical (v) scroll parameters were as follows:

Mouse.h

Change the declaration of move():

...
void move(signed char x, signed char y, signed char h = 0, signed char v = 0);
...

Mouse.cpp

Add the following to the report descriptor after the last INPUT message:

...
0x05, 0x0c,        //       USAGE PAGE (Consumer Devices)
0x0a, 0x38, 0x02,  //       USAGE (AC Pan)
0x15, 0x81,        //       LOGICAL_MINIMUM (-127)
0x25, 0x7f,        //       LOGICAL_MAXIMUM (127)
0x75, 0x08,        //       REPORT_SIZE (8)
0x95, 0x01,        //       REPORT_COUNT (1)
0x81, 0x06,        //       INPUT (Data, Var, Rel)
...

Change the definition of move():

void Mouse_::move(signed char x, signed char y, signed char h, signed char v)
{
    uint8_t m[5];
    m[0] = _buttons;
    m[1] = x;
    m[2] = y;
    m[3] = v;
    m[4] = h;
    HID().SendReport(1, m, 5);
}

The following terminal commands were also useful in testing these changes:

# List input devices
xinput --list

# List device capabilities
xinput --list <device-id>

# Watch for data sent from the device
watch -n 0.1 xinput query-state <device-id>


How to find integer inside a file with STRNCMP I'm trying to compare the int number 18 with strcmp but give to me wrong result, the program looking for char 18 and not for integer 18, how i can look for an integer with strcmp?

/*
 SD card read/write

This example shows how to read and write data to and from an SD card file
The circuit:
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4

created   Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe

This example code is in the public domain.

*/

#include <SD.h>

File myFile;
char buf[10];

char bufStringa[24];

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

 Serial.print("Initializing SD card...");
 // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
 // Note that even if it's not used as the CS pin, the hardware SS pin
 // (10 on most Arduino boards, 53 on the Mega) must be left as an output
 // or the SD library functions will not work.
  pinMode(10, OUTPUT);

 if (!SD.begin(53)) {
   Serial.println("initialization failed!");
   return;
 }
 Serial.println("initialization done.");

 // re-open the file for reading:
 myFile = SD.open("test.txt");
 if (myFile) {
   Serial.println("test.txt:");

   // read from the file until there's nothing else in it:
   int id=18;
   while (myFile.available()) {
      myFile.read(buf,2);
       if(strncmp(buf, id, 2) == 0) // i think the system give to me te char 18 and not the number 18 how to do this?
       {
           Serial.println("Match!");
           for(int i=0;i<10;i++)
           {
            Serial.print(buf[i]);

           }
            myFile.read(bufStringa, 24);
            for(int i=0;i<24;i++)
           {
            Serial.print(bufStringa[i]);

           }
          break;
       }
   }
   // close the file:
   myFile.close();
 } else {
  // if the file didn't open, print an error:
   Serial.println("error opening test.txt");
 }
}

void loop()
{
  // nothing happens after setup
}

Maybe make it as:

char id[] = "18";

This is if you want to find "18" in your file. That's what I understood from your question.

EDIT: I guess you want this http://playground.arduino.cc/Code/PrintingNumbers:

int num = 18;
char buffer[100]; // this will hold your number
itoa(num, buffer, 10);

Function description here. Also it's not to hard to make this your self for integers and it's a good exercise.