deprecated conversion from string constant to 'char*' What does this error means?
I can't solve it in any way.

  warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

As is my wont, I'm going to provide a bit of background technical information into the whys and wherefores of this this error.

I'm going to inspect four different ways of initializing C strings and see what the differences between them are.  These are the four ways in question:

char *text = "This is some text";
char text[] = "This is some text";
const char *text = "This is some text";
const char text[] = "This is some text";

Now for this I am going to want to change the third letter "i" into an "o" to make it "Thos is some text".  That could, in all cases (you would think), be achieved by:

text[2] = 'o';

Now let's look at what each way of declaring the string does and how that text[2] = 'o'; statement would affect things.

First the most commonly seen way: char *text = "This is some text";.  What does this literally mean?  Well, in C, it literally means "Create a variable called text which is a read-write pointer to this string literal which is held in read-only (code) space.".  If you have the option -Wwrite-strings turned on then you get a warning as seen in the question above.

Basically that means "Warning: You have tried to make a variable that is read-write point to an area you can't write to".  If you try and then set the third character to "o" you would in fact be trying to write to a read-only area and things won't be nice.  On a traditional PC with Linux that results in:

  Segmentation Fault

Now the second one: char text[] = "This is some text";.  Literally, in C, that means "Create an array of type "char" and initialize it with the data "This is some text\0". The size of the array will be big enough to store the data".  So that actually allocates RAM and copies the value "This is some text\0" into it at runtime.  No warnings, no errors, perfectly valid.  And the right way to do it if you want to be able to edit the data.  Let's try running the command text[2] = 'o':

  Thos is some text

It worked, perfectly.  Good.

Now the third way: const char *text = "This is some text";.  Again the literal meaning: "Create a variable called "text" that is a read only pointer to this data in read only memory.".  Note that both the pointer and the data are now read-only.  No errors, no warnings. What happens if we try and run our test command?  Well, we can't.  The compiler is now intelligent and knows that we are trying to do something bad:

  error: assignment of read-only location ‘*(text + 2u)’

It won't even compile.  Trying to write to read-only memory is now protected because we have told the compiler that our pointer is to read-only memory.  Of course, it doesn't have to be pointing to read-only memory, but if you point it to read-write memory (RAM) that memory will still be protected from being written to by the compiler.

Finally the last form: const char text[] = "This is some text";.  Again, like before with [] it allocates an array in RAM and copies the data into it.  However, now this is a read-only array.  You can't write to it because the pointer to it is tagged as const.  Attempting to write to it results in:

  error: assignment of read-only location ‘*(text + 2u)’

So, a quick summary of where we are:

This form is completely invalid and should be avoided at all costs.  It opens the door to all sorts of bad things happening:

char *text = "This is some text";

This form is the right form if you are wanting to make the data editable:

char text[] = "This is some text";

This form is the right form if you want strings that won't be edited:

const char *text = "This is some text";

This form seems wasteful of RAM but it does have its uses.  Best forget it for now though.

const char text[] = "This is some text";


Can i burn an Arduino sketch .hex directly using USBASP? I am unable to upload sketches to my Arduino Uno board using the upload option in the IDE. I have done quite a few tests to find the reason but everything seems to be working fine when tested separately. I found that I can program the ATMega328 board when placed on a breadboard using an USBASP progammer and avrdude. So will it work if I burn the .hex generated in Arduino IDE using avrdude and USBASP by placing the ATMega on a breadboard? I would then want to replace the IC on the UNO board back for my application. Thanks for your time and help in advance.

Sure you can - but you don't even need to remove the chip from the Uno.

The 6 pin header at the end of the board (used for SPI) is also the ISP header for the main chip. Just plug your USBASP into there (you can get adaptors for it for $0.99 off eBay) and program it direct.

I think there's even an option in the IDE's menu to select the USBASP as the programmer (or there used to be on earlier versions).


Why does my 23,032 byte Arduino sketch take 36.32 sec to upload via ISP to an Atmega328p on a breadboard w/code verification disabled? "Sketch uses 23032 bytes (71%) of program storage space. Maximum is 32256 bytes.
Global variables use 1342 bytes (65%) of dynamic memory, leaving 706 bytes for local variables. Maximum is 2048 bytes."
I have "verify code after upload" disabled. With this enabled, it takes an additional 20 sec to upload for a total of 56 sec.
Using Sparkfun's avr programmer with USBtinyISP, win 10, arduino ide, minicore library. Code is utilizing several libraries from Mozzi. External 16mhz crystal. Have set fuse bits on the chip to use the external clock using the following command: "avrdude -c usbtiny-p m328p -U lfuse:w:0xFF:m"
Seems like it should be faster if truly uploading at 115200 bits / sec. But maybe I'm missing something in how this works.
Thanks !!

ISP programmers typically default to low ISP clock rates.  Often something like 10khz, sometimes slower, probably to just work by default with very slowly clocked AVR chips.  The ISP clock rate must be about one eigth that of the AVR's clock.  For example, by defaulting to a low rate like 10Khz, the programmer will successfully communicate with an AVR clocked at 125KHz with some margin.   Around 4 KHz would work with a 32.768 KHz watch crystal.
Look in avrdude documentation for the -B option.  Note uppercase 'B', this is the option for changing the ISP speed, not lowercase -b which is for the PC to programmer (or bootloader) baud rate.   Not all programmers support -B, but many do.
UPDATE
Well, I dug around the USBtinyISP code and in avrdude and it looks like the default value for -B is 10.  So 10uS.  The way this value is used in the USBtinyISP code is for high or low period, rather than total clock period.  So it's about 20uS per bit, or 50kHz.  If that's your rate, then the plain clocking of the SPI data only accounts for about 3.7 seconds.  So that does cast doubt on this idea.
But, it still may be worth double checking that it is operating with the value 10 and not something larger.  Just to put this in perspective: the maximum -B value is apparently 250, which would result in 2kHz ISP clock rate and about a minute and a half to clock out your roughly 23 KByte.
More findings: Per byte SPI overhead
Each byte of the flash pages is being delivered into the ISP interface by way of 4-byte long SPI commands.  The firmware for the programmer has the following code in it for writing a page in its spi/main.c file where you can see it calling spi( cmd, res, 4 ) :
extern  void    usb_out ( byte_t* data, byte_t len )
{
    byte_t  i;
    uint_t  usec;
    byte_t  r;

    for ( i = 0; i < len; i++ )
    {
        cmd[3] = data[i];
        spi_rw();
        cmd[0] ^= 0x60; // turn write into read
        for ( usec = 0; usec < timeout; usec += 32 * sck_period )
        {   // when timeout > 0, poll until byte is written
          spi( cmd, res, 4 );
            r = res[3];
            if  ( r == cmd[3] && r != poll1 && r != poll2 )
            {
                break;
            }
        }
    }
}

This code is used to deliver data to the flash page buffer during ISP programming.
You can see a comment in avrdude's code explaining that each byte becomes a 4-byte SPI transaction as an aid to explaining their calculation for a communications timeout with the programmer.  The following is in avrdude's usbtiny.c file for the usbtiny_paged_write function.
if (usb_out(pgm,
            function,       // Flash or EEPROM
            delay,          // How much to wait between each byte
            addr,           // Address in memory
            m->buf + addr,  // Pointer to data
            chunk,          // Number of bytes to write
            32 * PDATA(pgm)->sck_period + delay  // each byte gets turned into a
                                 // 4-byte SPI cmd  usb_out() multiplies
                                 // this per byte. Then add the cmd-delay
            ) < 0) {
  return -1;
}

To be clear, these two functions have the same name but are in fact two different functions; the former running in the programmer the later is running in avrdude.
So there is in fact substantial SPI transaction overhead in just delivering data into the page buffer.  Beyond that there's a second USB and SPI transaction to commit the page buffer to flash.


How to stop program while Servo is rotating If I code like this:

motor.write(0);
Serial.println("Before");
motor.write(180);
Serial.println("After");

Both "Before" and "After" is instantly printed, while the motor is still rotating.
I want "After" or whatever statement to be executed AFTER the motor
reaches 180 degree.
How can I implement this? Is it possible to read Servo's statement?

Btw, I don't want to put delay after write(), so other than that strategy.

How can I implement this? Is it possible to read Servo's statement?

No, it is not possible. When you do a servo.write() it just changes the PWM duty cycle. It's then up to the servo to use that to set its position. The Arduino has no concept at all of the current position of the servo.

  Btw, I don't want to put delay after write(), so other than that strategy.

The only other way, besides delaying or otherwise using millis() to wait for a predefined period after your write would be to implement some form of feedback between the shaft of the servo and the Arduino. Maybe a potentiometer, or rotary encoder would do the job.


Grove Base Kit Multiple I2C Connection I tried to connect two modules that require I2C connection and they won't work at the same time.
I used the Arduino Sensor Kit - Base. This kit does not need any connection, you just have to code to get your desired output. I wanted to display the Air Pressure (BMP280) module values to the 0.96" OLED Display, however, it is refusing to run both the air pressire and the OLED display at the same time. Only running one module (either Air pressure or OLED) at a time makes it work. Does it have something to do with how the I2C connection is wired on the board?
#include "Arduino_SensorKit.h"

void setup() {
  // put your setup code here, to run once:
  Oled.begin();
  Oled.setFlipMode(true);
  Oled.setFont(u8x8_font_7x14B_1x2_r);

  Pressure.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
  Oled.clear();

  Oled.setCursor(0, 10);
  Oled.print("Temp: ");
  Oled.print(Pressure.readTemperature());
  Oled.print(" C");
  Oled.setCursor(0, 20);
  Oled.print("Pres: ");
  Oled.print(Pressure.readPressure());
  Oled.print(" Pa");
  Oled.setCursor(0, 30);
  Oled.print("Alti: ");
  Oled.print(Pressure.readAltitude());
  Oled.print(" m");

  delay(1000);
}

What I did:

Test to see if Air Pressure will still work while both Air Pressure and OLED is connected by using Serial.begin(). Now I know that only the OLED does not work when both modules are connected.
Changed order of initialization. Same result: Air Pressure works but not OLED

About two weeks ago there was a change in the Arduino_SensorKit Library that introduced an error with the instanciation of the Oled object.
I found the error in the release (v1.0.6) of the library. The previous release (v1.0.5) could cause another issue, as it uses a software I2C. I doubt the hardwired sensores are connected with the correct pins. But I have no hardware, so I can not check this.
I propose a workaround to see, if the identified issue caused your observations.
#include "Arduino_SensorKit.h"

U8X8_SSD1306_128X64_NONAME_HW_I2C Oled2;
// if the line above does not work
// comment it and uncomment the following line.
// U8X8_SSD1306_128X64_NONAME_HW_I2C Oled2(U8X8_PIN_NONE);

void setup()
{
  Oled2.begin();
  Oled2.setFlipMode(true);
  Oled2.setFont(u8x8_font_7x14B_1x2_r);

  Pressure.begin();
}

void loop()
{
  Oled2.clear();

  Oled2.setCursor(0, 10);
  Oled2.print("Temp: ");
  Oled2.print(Pressure.readTemperature());
  Oled2.print(" C");

  delay(1000);
}

Could you please try out and report your experience.
If it would work, I can support the fixing of the issue.


Is it possible to pass HIGH and LOW values as parameter in a function? I've created the following function:

void runMotor(int _dir, int _step, int wait){
  digitalWrite(_dir, HIGH);
  for (int x = 0; x < 3200; x++) {
    digitalWrite(_step, HIGH);
    delayMicroseconds(wait);
    digitalWrite(_step, LOW);
    delayMicroseconds(wait);
  }

In the first line inside the function I used the value HIGH as a fixed value. I would like to know if there's a way to pass the values HIGH and LOW as a parameter in this function. Is it possible?

Or should I just create a new function to rotate my step motor to the other side?

digitalWrite expects the pin and value to be uint8_t type. So you can certainly pass LOW or HIGH to functions.

For example:

void runMotor(int _dir, int _step, int wait, uint8_t value){
  digitalWrite(_dir, value);


Arduino Leonardo as USB Keyboard with WiFi module I have two PCs: the first is connected to the Arduino via WiFi, this will instruct the Arduino what keys to send, and the second PC is connected to the Arduino via USB that will act as a USB Keyboard for the PC to receive keystrokes. Is it possible to use Arduino Leonardo as a USB Keyboard connected to a PC with WiFi module connected to another PC? Do I need other components or modules for this to work?

I have searched the possibility of keystrokes and WiFi connection as separate projects but can't seem to find a project that has this scenario.

I also consider using Teensy with WiFi module if it is feasible. If this is not possible, are there any workarounds? Or other devices I can use? Thanks in advance.

EDIT: I am also checking Raspberry Pi Zero as an alternative. Is the project more probable with this or is it better to stick with Arduino?

Its always very unlikely that someone will have done exactly the same project as you, which is why you need to break it down.

You want to talk to an Arduino over Wifi.
You want he PC to send commands to the Arduino.
You want to make the Arduino act as a keyboard.

I know each of those three parts in on this site, so that should help answer a lot of questions on how to do it, but obviously some of the solutions may conflict so you'll have to discard them.

You can use an ESP8226 - the Arduino talks to it via serial (software serial).
You will need an application (c# will be easiest for Windows) that will send data to the Arduino.  You need to design and implement a protocol, using REST may be a good idea.
I've never done it and don't know how, but I think I read there is a HID Library (Human Interface Device aka Keyboard or rat) and that makes thinks easier.

As to what hardware you could use there may well be performance constraints, that affect what hardware you can use.  I suspect the lower spec Arduiano's may introduce a lag that may not be acceptable.  Since you want to do it over Wi-Fi, you might want to have a look at the ESP8226, which can be programmed like an Arduino and has native Wi-Fi.  I'm not sure if you can use it as a HID though.


Arduino , python , pyfirmata , standard firmata Is there a way to change arduino analog reference to EXTERNAL IN PYTHON using pyfirmata or any other library ?
Necessary Links : https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/
My sensor has a 3.3 volt operating voltage , my arduino has a 5 volt operating voltage.
As such in arduino using C++ and arduino module the scaling can be done using analogReference(External) and providing reference voltage to analog read?
IS there any equivalent to this in python, pyfirmata ?

No, not as far as I know. The firmata protocol does not include a command to set the analog reference. However, you can of course modify the firmata firmware to your liking. In the simplest case, just add the appropriate command to the setup() function of the main .ino.


Atmega328P Prescaler to Microseconds For a bitbanging project I'm working on, I need to measure microseconds as accurately as possible. The function micros() won't work for me here because of the unpredictable times at which it might roll over. I have been using this project by Louis Frigon as an example:

https://web.archive.org/web/20140627135927/http://www.sigmaobjects.com/toyota/

In this document he sets his Atmega8's prescaler value:

// Timer 0 prescaler = 8 ( 1 count / us )
TCCR0 = _BV(CS01);

Do I understand that after these instructions, TCNT0 counts up by nearly precise microseconds?
If so, what math could I use to set my prescaler for measuring microseconds? The 328P has a higher clock speed, does that mean I won't be able to do this?

The 328P has a higher clock speed

The 328P will run at whatever speed you clock it, up to a maximum that
depends on the supply voltage. Most 328P-based Arduinos are clocked at
16 MHz though.

  what math could I use to set my prescaler for measuring microseconds?

You can't. You would have to set the prescaler to 16 if you want the
timer to count microseconds. You can set it to 8 or to 64, but there is
no intermediate setting in between.

Maybe you could leave the prescaler at 8 and count half-microseconds
instead?

Edit: On the 328P, Timer 0 has two control registers, named
TCCR0A and TCCR0B. To set it to normal counting mode at F_CPU/8,
you have to:

TCCR0A = 0;
TCCR0B = _BV(CS01);

If you are programming in plain C, the first line is not needed (but it
won't hurt either), as the initial value of TCCR0A is zero on reset.
If you are using the Arduino core library (and you write setup() and
loop() instead of main()), then you do need this first line, as the
Arduino core configures Timer 0 for PWM at 977 Hz. But note
that the Arduino core also uses Timer 0 for timekeeping
(millis(), micros() and delay()). Thus you may want to use another
timer.

You could switch to Timer 2 by replacing every “0” with a “2” on
the register and bit names of the two lines above. Then you would also
replace every occurrence of TCNT0 in the code with TCNT2.


Lifespan of a hot microchip I'm currently building my own Home Automation System with a bunch of Arduinos and Relais, all of them wired to Ethernet "Shields". The casing I am printing on a 3D printer.

The Arduinos work great with those Ethernet "Shields", but the ENC28J60 chip on those Ethernet boards get quite hot. I am measuring 79.5°C approx.
In the plastic casing, I expect that they reach higher temperatures (because it's closed and has no ventilation whatsoever).

Since I am building this as a permanent solution (House wiring is now all newly adapted and I have no way back), which lifespan can I expect from those Ethernet boards?

The datasheet of that chip is saying that it's rated up to 85°C, but what does this upper rating mean? Will it stop working at this point, or only begin to degrade it's lifetime at this point?

EDIT: I have no space to put a dissipation block on those chips, because the casing is so tight.

The reliability data is typically not in the product datasheet but in pen whitepapers. Generally speaking life span goes down exponentially as temperature rises. For some high temperature semi conductors ( designed specifically for high temperature applications) you are talking about hubdreds or thousands of hours at rated temperatures.

That should give you some sense as to what to expect.


how to use hx-53 (IR Transmitter Infrared Sensor Module) with ESP32? ESP32 tx2 (pin17) and rx2 (pin16) uses 3.3v based signals.

HX-53 data connect to tx2, gnd to gnd and vcc to vin(5v).

But as i can understand HX-53 data input should be 5v based.

How can i solve this problem?

HX-53: https://www.amazon.com/Electronic-Infrared-Emission-Transmitter-Arduino/dp/B07PJC7WSQ

Best regards.
GA

The HX-53 look like a IR LED and a current limiting resistor on a small PCB.

It also has a LED and a resistor in series for indication when the invisible IR diode is on or off.

So you can change the resistor to a lower value to match the 3,3 volt output from the ESP32.

Resistor values:

221 = 220 ohm   = IR LED
102 = 1000 ohm  = SMD indicator LED

So replace the 220 ohm with something near 75 ohm.

HX-53


Are there any standard ways of reporting a runtime error? I'm new to Arduino but I'm an experienced programmer. I'm wondering if there are any common functions for reporting errors in Arduino programs? For example, in JavaScript we have the alert() function, or on Unix you can write a message to standard error and exit.

Ideally, if the serial port is available then an error message would be printed there, or if there is an LED then maybe we should blink it. This would need to be configurable based on what the programmer wants to do with available hardware.

Looking the example sketches, error reporting seems pretty horrible. I'm wondering if any libraries handle this better?

As pointed out by Majenko in a comment, you can hardly define a standard
facility for error reporting when you don't know what kind of I/O
hardware will be available on any particular project. Printing to the
serial port is the most common method though, as it tends to always be
available during the development phase, while the Arduino is tethered to
the development computer. I personally tend to just do something like

Serial.println(F("Error: the warp field coil is busted."));

and be consistent with the error prefix, so that a program receiving
this can tell it's an error by matching the line against /^Error: /.

While it is OK for user code, reporting errors through Serial is
certainly not a good practice for library code. Alas, it is done way
too often in Arduino libraries. I've seen at least one library (don't
remember which one) that allows the user to provide a reference to a
Print object (defaulting to Serial) to be used for this purpose.
This is way better, as it allows the user to handle the error messages
any way she chooses. It is also very easy to turn off the error
reporting altogether by implementing a do-nothing Print, which would
be a /dev/null of sorts.

Note that the avr-libc allows you to print to stderr, as long
as you have first implemented stderr->put... While this method is the
closest you can get to the standards you are used to, it may not be
portable to non-AVR Arduinos. And it is worth noting that we tend to
avoid the printf() family of functions on Arduinos, as they tend to be
quite large compared to the print() and println() methods.


Flickering LED when servo moves I just got to play around with Arduino lately so I'm really new on this stuff and sorry for the grammar error.

I got a work where I need to turn the LED on all the time, my plan is to add a slow fade in and fade out later but the problem occurs when I add the servo.

Everytime servo starts moving slowly or fast the LED kinda flickering/dim like it lost power and come back to normal after the servo stops moving.

Here's the scheme I used and the code, I only change some delay to 5ms and so to test it out but no matter what the led is keep flickering.

Im using nano v.3 clone if its matter.

#include <Servo.h>
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 100;    // variable to store the servo position
int ledpin3 = 3;

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  pinMode(ledpin3, OUTPUT);
}

void loop() {
  digitalWrite(ledpin3, HIGH);
  delay(1000);

  for (pos = 99; pos <= 150; pos += 1) { // goes from 0 degrees to 180 degrees
                                         // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable ‘pos’
    delay(15);                       // waits 15ms for the servo to reach the position
  }

  for (pos = 150; pos >= 30; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable ‘pos’
    delay(15);                       // waits 15ms for the servo to reach the position
  }

  for (pos = 30; pos <= 99; pos += 1) { // goes from 0 degrees to 180 degrees
                                        // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable ‘pos’
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

If you are powering the arduino via usb try not to do that or plug it in to an usb 3.0 (and higher) port. The reason for this is that the servo draws a lot of power and the standard usb 2.0 with 0.5A can't handle the load and you got an voltage drop. And in that period of time the led goes off. usb 3.0 (and higher) can handle up to 1.5A so this souldn't be an error.


How to use a digital RGB LED Strip? I know this is probably a little bit basic but I need SERIOUS help with using my new led strip. You can see here the type of strip I have, and the packet.

It's difficult because it looks slightly different to all the other ones I've seen in tutorials so I don't really know where to start now...All I've done is cut off the ends of the wires already on there and replace them with the regular pins that I can use on the Arduino and breadboards too. Where do I have to go from here? Are there any code libraries I need to use?

As far as I understand the DAT (Green wire) is a digital data wire. Try the following:
1. VCC to +5V pin
2. GND to GND pin
3. DAT to 2 Digital pin.

Then try to change the state of the 2 digital pin from high to low and see if anything happens... That's what I would start out with.


Physical dimensions(size) of the new MKR1000 board? Anybody here knows the physical dimensions(size) of the new Aduino MKR1000 board?

If the diagram on the main page is to scale, then it's approximately 2.2 inches by 1.0 inches.


Making three LED's blink at given times I have a breadboard connected to an Arduino Uno, 220k resistors connected to an led, of course it has a common ground and a pin connected to 5v. All pins are digital.

Now, I want led 1 to turn on for one second, the next led for two seconds and the next for three seconds, but that means, when the second led which has to be on for two seconds then the first led will come back on after one second has past on the second led, the third led would be on for three seconds, so the second led will also be on when two seconds pass and the first would be on when one second passes. So basically, all leds are on for their given duration.

How do I do this? I have been trying to do this since three days. It would be a pleasure if someone helps me out. Thanks.

int ledPin1= 2;
int ledPin2 = 4;
int ledPin3 = 7;

void setup(){
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  }

  void loop(){
  digitalWrite(ledPin1, HIGH);
  delay(500);
  digitalWrite(ledPin1, LOW);
  delay(500);

  digitalWrite(ledPin2, HIGH);
  delay(1000);
  digitalWrite(ledPin2, LOW);
  delay(1000);

  digitalWrite(ledPin3, HIGH);
  delay(1500);
  digitalWrite(ledPin3, LOW);
  delay(1500);
    }

So far this is the code. But it delays the whole program. Need leds on at given times.

You could start by drawing a time graph, like this:

LED 1   # # # # # # # # # # # # # # # # # #
LED 2    ##  ##  ##  ##  ##  ##  ##  ##  ##
LED 3      ###   ###   ###   ###   ###   ###
        <-period 1-><-period 2-><-period 3->

As you see on the graph, the whole sequence repeats itself every
12 seconds. Then, you can just write down all the pin toggles for
12 seconds and let the loop repeat itself:

void loop() {
    digitalWrite(ledPin1, HIGH);
    digitalWrite(ledPin3, LOW);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, HIGH);
    delay(1000);
    digitalWrite(ledPin1, HIGH);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, HIGH);
    delay(1000);
    digitalWrite(ledPin1, HIGH);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, HIGH);
    delay(1000);
    digitalWrite(ledPin1, HIGH);
    digitalWrite(ledPin3, LOW);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    delay(1000);
    digitalWrite(ledPin1, HIGH);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, HIGH);
    digitalWrite(ledPin3, HIGH);
    delay(1000);
    digitalWrite(ledPin1, HIGH);
    delay(1000);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    delay(1000);
}

This was the simple, albeit tedious solution.

The smart solution is to go through the Blink Without Delay Arduino
tutorial. You will see that, once you start using millis() instead of
delay() for managing your timings, blinking three LEDs instead of one
is completely trivial.


Arduino pins not working I'm building my first arduino project and I encountered a strange problems;

I build a haunted house based upon that instructables tutorial:
https://www.instructables.com/id/Control-Your-Halloween-Decorations-With-Arduino/

Every prop works, I tried to light them on and off (it works), but when I try to use all of them, a few doesn't work.

There is my code; Is it something I'm doing wrong?

int propSqueDans = 4;
int propClownImmo = 5;
int propClownJambes = 6;
int propSqueBal = 7;
int propSqueMini = 8;
int propSpider = 9;
int propChauSou = 10;
int propFantChai = 11;

int SensorPin = 3; // sensor connected to analog pin 3
int SensorVal = 0; // variable to store the value read

void setup() {
  pinMode(propSqueDans, OUTPUT);// sets the digital pin as output
  pinMode(propClownImmo, OUTPUT);
  pinMode(propClownJambes, OUTPUT);
  pinMode(propSqueBal, OUTPUT);
  pinMode(propSqueMini, OUTPUT);
  pinMode(propChauSou, OUTPUT);
  pinMode(propFantChai, OUTPUT);
  pinMode(propSpider, OUTPUT);
  Serial.begin(9600);

  }

void loop() {
    SensorVal = analogRead(SensorPin); // read the input pin

    if (SensorVal >100) {
    Serial.write("Danse + Clown Immo \n");
    digitalWrite(propSqueDans, HIGH);
    digitalWrite(propClownImmo, HIGH);
    delay(10000);
    Serial.write("Spider + Fangtôme + Clown jambes \n");
    digitalWrite(propSpider, HIGH);
    digitalWrite(propFantChai, HIGH);
    digitalWrite(propClownJambes, HIGH);

    delay(5000);
    Serial.write("Squelette balance + sque mini \n");
    digitalWrite(propSqueBal, HIGH);
    digitalWrite(propSqueMini, HIGH);

    delay(5000);
    Serial.write("Chauve souris \n");
    digitalWrite(propChauSou, HIGH);

    delay(20000);

    digitalWrite(propSqueDans, LOW);
    digitalWrite(propClownJambes, LOW);
    digitalWrite(propSqueBal, LOW);
    digitalWrite(propSqueMini, LOW);
    digitalWrite(propChauSou, LOW);
    digitalWrite(propFantChai, LOW);
    digitalWrite(propSpider, LOW);
    digitalWrite(propClownImmo, LOW);
    delay(5000);
    }

  }

Thank you for your help !

My best guess (not knowing what the pins are driving) is that your trying to draw too much current from the Arduino gpio.

Ref: https://playground.arduino.cc/Main/ArduinoPinCurrentLimitations


How to fill a triangle using the LCD5110 Graph library? Good day! I'm currently trying to create a small 3D engine using C++, an Arduino UNO as well as a Nokia 5110 display with a library. Now I have successfully drawn a cube using triangles, but I want to fill the triangles to add proper lighting. My method for drawing triangles is the following:

LCD5110 lcd(8,9,10,12,11);

void DrawTriangle(int x1, int y1, int x2, int y2, int x3, int y3) {
 lcd.drawLine(x1, y1, x2, y2);
 lcd.drawLine(x2, y2, x3, y3);
 lcd.drawLine(x3, y3, x1, y1);
}

My library hasn't got a triangle draw or fill method unfortunately. I have no idea how I could fill a triangle so I hope for help.

Thanks in advance...

NOTE:
Please keep it simple.

NOTE NR.2: I have already asked this question at StackOverflow but I haven't got a good answer so I will try it again.

After tinkering around for hours I have finally found a great way to fill triangles! Here we go:

for(int x = x1; x<=x2; x++) {
    for(int y = y1; y<=y2; y++) {
     lcd.drawLine(x3, y3, x, y);
    }
}

Great!


New OLED seems dead, how can I be sure? I bought this 2.8" OLED from Aliexpress a few weeks ago: https://www.aliexpress.com/item/32988174566.html?spm=a2g0s.9042311.0.0.72304c4dAWcHG8

And after a ridiculous amount of searching for a datasheet, I came across this one that seems to match the board I bought: https://www.buydisplay.com/download/manual/ER-OLEDM028-1_Series_Datasheet.pdf

Wiring up pins 1 and 2 to ground and 3.3V on a breadboard, I'd expect something to happen with the display, but I get nothing. The display is in 8080 mode, so I wire everything up to a standard UNO board and power everything on. Still nothing. Try changing the power to 5V, no joy.

During my testing, I noticed the back of the display is getting hot. Not sure if that's a good thing or not yet.

So what's the best way to 1) determine if the datasheet I found is correct? 2) check if the OLED is just broken? I don't have a ton of experience with these displays yet, so I'm not sure if just powering the thing on should net some visual response.

The datasheet you have found is not for the same display. Yes, it's similar, and yes, it has the same actual OLED display unit on the board, but the PCB is different. So you cannot assume that the pinout is the same.

The fact that it's getting hot tells me that you have probably wired something wrong and you are injecting voltage into it somewhere where voltage doesn't want to be injected.

To find if an OLED is working you have to actively wire it up.  With an LCD you can just give it power and you should be able to see some visual indication that it's working (back light, some shadowing of the display matrix, etc). But with an OLED you can't do that.  An OLED is made up of a matrix of LEDs which are either on or off. By default they are off, and when they are off it's no different to there being no power. That's the big benefits of OLED displays - low power consumption and true black.

To get any kind of indication that the display works you both need to wire it 100% correctly and program the Arduino in the right way to actively drive it by displaying something on the screen.  My usual test program when working with a new screen is to simply print millis() in the top left corner.


5V usb surge protection for circuit board? I want to use a mini usb jack to power my device off board, but I want to make sure that the usb power coming in is not any higher than the 5V. I've read a bit about polyfuses but I am unsure if they would be useful for this scenario. Thanks!

A polyfuse will limit current not voltage.

There are transient protection diodes which switch on if voltage exceeds a given level, which are often used in conjunction with a polyfuse. The diodes cause excessive current to flow, effectively turning on the polyfuse for extended overload, or just absorbing shorter transients. The Raspberry Pi uses a SMBJ5.0A device to suppress transients.

You should NOT need any of this if you use a reasonable power supply.


Using a MIDI connector both as MIDI In and Out (not simultaneously) I asked this question also in Electrical Engineering (stack exchange), however on question is more appropriate on this board (question 5). For completeness, I kept all questions intact, but made question 5 bold.

Electrical Engineering StackExchange Question Link: Using a MIDI connector both as MIDI In and Out (not simultaneously),

In my current (Arduino) project I have (currently) 3 MIDI INs and 2 MIDI OUTs. However, it would be nice if I can configure each of the MIDI connectors as IN or OUT by software (Arduino).

The circuits I am using are:

And

What I would like is to use the connector shown in the above picture as MIDI In OR MIDI out. I have not tried it yet, since I have too many doubts and I do not want to break a component. However, I thought about it (with my limited electronic knowledge), and I think:

Pin 2 afaik for MIDI In, normally has +5V. In the MIDI Input circuit it is not connected, but in the MIDI Output circuit, it is connected to GND. I don't think this is good when being used as MIDI out, resulting in a short circuit (?). So I guess I have to make it +5V when used as MIDI Input and GND when used as MIDI Output (so putting HIGH or LOW 'digital' for Arduino).
Pins 1 and 3 remain in both circuits untouched (so I assume I can do the same).
Pin 4 and 5 is a bit tricky, since they are connected. I think I have to use one or two transistors to create two alternative paths for pins 4 and 5 for MIDI Input and Output. Or can I just set a specific voltage on pins 4 and 5 when used as MIDI In or Out? (and what would those values be?).
For the MIDI input, an optocoupler is used, while for MIDI output, directly the Arduino is used. I wonder if I have to use for both an optocoupler (since people might connect it accidentally to a MIDI output from a MIDI device.

5. I'm not sure how to handle the RX and TX pins ... for 5 MIDI devices, I would need to use 5 RX and TX pins, but the Arduino (Mega) only has 4 of each. But this is probably a question for the Arduino board.

I suggest you have a look at the 4051 or 4052 chip (datasheet). The 4051 is a 1:8 analog multiplexer while the 4052 contains two 4:1 multiplexers. So basically it allows you to switch one pin on your Arduino to any out of 4 or 8 MIDI circuits.

In the case of TX, it's really simple. You just need a pullup resistor on each output so that the pins don't float when not switched to.

In the case of RX, you have to make sure that you don't miss any transmissions. If your MIDI sources are not sending simultanously, that's easy as well... but probably they are. In that case you cannot use an existing RX UART. Since MIDI is very slow, you could still switch back and forth between the inputs and catch all the bits (you would be writing a software UART then). But if you're not short of pins, it would be much easier to just use SoftwareSerial for one input.


RFM69HCW 915 MHz radio module: Sending a stream of int values rather than char[ ] I'm trying to send a stream of int values (0-4096) from one arduino to another using an RFM69HCW module.

Here's my main code:

#include <RFM69.h>
#include <SPI.h>
#define NETWORKID     0   // Must be the same for all nodes
#define MYNODEID      1   // My node ID
#define TONODEID      2   // Destination node ID
#define FREQUENCY     RF69_915MHZ
#define ENCRYPT       true // Set to "true" to use encryption
#define ENCRYPTKEY    "TOPSECRETPASSWRD" // Use the same 16-byte key on all nodes
#define RFM69_CS      10
#define RFM69_IRQ     2
#define RFM69_IRQN    0  // Pin 2 is IRQ 0!
#define RFM69_RST     9
#define IS_RFM69HCW   true
#define USEACK        true // Request ACKs or not
#define LED           9 // LED positive pin
#define GND           8 // LED ground pin
#define PULSEPIN      0 // Heart Rate Monitor at pin A0

RFM69 radio = RFM69(RFM69_CS, RFM69_IRQ, IS_RFM69HCW, RFM69_IRQN);
String pulsearray;
bool recHR = true;
unsigned long oldtime = 0;
int interval = 5000;
static int readtime = 3000;
static int sampletime = 10; // 1000/this is the thing
static int txinterval = 1000; // delay between transmissions

void setup() {
  initSerial();
  initLed();
  initRadio();
}

void loop() {
  unsigned long newtime = millis();
  if (!recHR && newtime - oldtime >= interval) {
    recHR = true;
    oldtime = newtime;
    Serial.println("recording HR now");
  }

  while (recHR) {
    unsigned long newtime = millis();
    if (newtime - oldtime >= sampletime) {
      readhr();
    }
    if (newtime - oldtime >= readtime) {
      recHR = false;
      oldtime = newtime;
      Serial.println("stopped reading HR");
    }
  }
}

And the function I'm using:

void readhr() {
  for (int i = 0; i < 20; i++) {
    int pulse = analogRead(PULSEPIN);
    pulsearray = pulsearray + pulse;
    pulsearray = pulsearray + '\n';
    Serial.println(pulse);
  }
}

The library function sendWithRetry() requires the following arguments:

bool RFM69::sendWithRetry(uint8_t toAddress, const void* buffer, uint8_t bufferSize, uint8_t retries, uint8_t retryWaitTime)

I would like a way to set up a buffer which can be transmitted in multiple packets during the 5 second analogRead() downtime.
Using a string as my buffer doesn't work when I try to transmit the first n (<60) characters in the String. I've also tried using a char[ ] as my buffer (a lot more troublesome when storing int values) but it still gives the same error:

exit status 1
no matching function for call to 'RFM69::sendWithRetry(int, String&, unsigned int)'

You need to send the address of a buffer and the size, in bytes, of that buffer. What that buffer consists of is neither here nor there.

If you have an array of 10 ints you have a 20 byte buffer (since one int is 2 bytes on an 8-bit Arduino).

So you just pass it the address of the buffer (which as an array it is already just an address) and the size of that buffer:

int values[10];
// whatever to fill the array
RFM69::sendWithRetry(20, values, 20, 4, 1000);

As long as the array is statically created (e.g., a global variable with a fixed number of entries) you can use sizeof() to get the size in bytes:

RFM69::sendWithRetry(20, values, sizeof(values), 4, 1000);

As long as you receive at the other and using the same type of buffer it should be completely transparent.

To keep the system cross-platform and able to run on an Arduino that is either 8 or 32 bits and have them completely interoperable it is best to use variables with a fixed size. Instead of int use int16_t which is always 2 bytes and signed on every platform everywhere:

int16_t values[10];

Or use uint16_t if you want it unsigned.


L298 with stepper.h disable break I try to control a Stepper motor with an arduino and a L298. I use the library stepper.h and it works well but i have a problem : the L298 become very hot. So i want to disable the break (the thing that we can't turn the motor by hand), but i don't know how to do this.
Do you have an idea ?
My code is simple :

#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  // set the speed at 60 rpm:
  myStepper.setSpeed(60);
  // initialize the serial port:
  Serial.begin(9600);
}

void loop() {
  // step one revolution  in one direction:
  Serial.println("clockwise");
  myStepper.step(stepsPerRevolution);
  delay(500);

  // step one revolution in the other direction:
  Serial.println("counterclockwise");
  myStepper.step(-stepsPerRevolution);
  delay(500);
}

I took it from here : https://coeleveld.com/arduino-stepper-l298n/

Thanks !

There is no facility in the stepper library to do what you want - however the stepper library just sequences IO pins in the right order.

There's nothing to stop you just placing those same IO pins in a different state - the library won't care.

void sleepStepper() {
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
    digitalWrite(10, LOW);
    digitalWrite(11, LOW);
}

That will effectively set every port of the L298 LOW, which is equivalent to "brake" mode on a normal DC motor, or "not actively driving" on a stepper (not perfect freewheel, there is still some flyback braking).

Another option is to connect the EN pin(s) of your L298 chip to a GPIO and use that to turn the whole system on and off. That will disconnect the drivers from the motor and give you even less movement resistance than the "all low" method above.


When I call the tone function on a Uno, why do I not have to declare the pinmode in setup? When I call the tone function on a Uno, why do I not have to declare the pinmode in setup? Like so:

// Simplest tone
void setup() {
}

void loop() {
    tone (8,500); //on pin 8 output 500 Hz
}

Because the tone(hertz) code initializes the pinmode, along with the timer/counter control registers to produce the appropriate frequency.

void tone(uint8_t _pin, unsigned int frequency, unsigned long duration)
{
  uint8_t prescalarbits = 0b001;
  long toggle_count = 0;
  uint32_t ocr = 0;
  int8_t _timer;

  _timer = toneBegin(_pin);

  if (_timer >= 0)
  {
    // Set the pinMode as OUTPUT
    pinMode(_pin, OUTPUT);
   ...

See Tone.cpp - line 255 for the source.


Hall effect sensor direction detection using arduino I'm using a hall effect sensor A1356 (linear application) to measure the amount of fluid in a container. The fluid is in constant use. My doubt is I'm placing the sensor and the magnet assembly in place, such that when it is exactly half filled, the magnet's center will align with the center of the sensor. In this condition I get 100% duty cycle output from the sensor.

Condition 1: If the fluid is filled then the magnet moves above the sensor and the duty cycle reduces say to 90%.

Condition 2: If the fluid is consumed then the magnet will move below the sensor and the duty cycle reduces to say 90%.

How do I differentiate between the rise and fall of the fluid? Or is there a better way of orienting the magnet and the sensor such that this problem could be avoided?

I'm interfacing it with an Arduino UNO

According to the data sheet (see below) the no-field PWM output is mid-range; north poles reduce it & south increase.

So if you had an arrangement whereby the float had north down & south up, ie a vertical bar-magnet, this would presumably give a rise-before-0 or fall-before-0 at the float vanishes, or a fall-to-minimum an rise-to-maximum as the float centres? The bit in the middle could be interesting!

From the datasheet:
"The presence of a south polarity magnetic field,
perpendicular to the branded surface of the package face,
increases the output duty cycle from its quiescent value toward
the maximum duty cycle limit. The amount of the output duty
cycle increase is proportional to the magnitude of the magnetic
field applied. Conversely, the application of a north polarity
field decreases the output duty cycle from its quiescent value."


Can I power ESP8266 with more than 3.5 V? I am concerned whether I need to use a voltage divider to power my ESP8266 module. My concerns stem from the warnings that I have heard in multiple tutorials. Everyone seems to regard the ESP8266 as being very sensitive to supply voltage.

Has anyone use the ESP8266 with an supply voltage greater than 3.5 V? What were the effects? Is it even necessary to make a voltage divider?

I am asking because my application has limited real estate.

The datasheet usually is definitive on the allowable range of voltages.

Look in Section 5.1: Electrical Characteristics.

Working Voltage Value:

Min: 2.5 V
Typical: 3.3 V
Max: 3.6 V

If you have to feed in signals that could go higher than 3.3 V in normal operation, you need to either clamp it with Zener diodes, or use a voltage divider.

If you are asking about powering the chip with more than 3.3 V, don't. You can get away with a 3.3 V linear regulator and 2 capacitors so that you are powering it with no more than designed supply voltage.


I have cooked 3 regulators applying 12 V to RAW pin. Am I doing something wrong or did I get a bad batch? I'm trying to make a simple keypad lock that has a 12 V magnetic lock.  I supplied 12 V to the RAW pin on the Pro Mini with plans to actuate the relay with the 5 V from VCC pin.  The lock was grounded on the terminal strip that the 12 V came from, and then the positive 12 V was switched through the relay.

Everything was working well until I powered the board through the RAW pin with 12 V.  When I did that all three failed the smoke test.

My question is, am I doing something incorrectly or did I happen to get a bad batch (all three of the boards came in the same shipment, I assume they came from the same lot)?

The Pro Mini's 5V regulator (MIC5205) can supply a maximum of 150 mA, from which the Pro Mini uses about 20 mA, leaving around 130 mA for other applications.

Check the data sheet of the relay, to get the maximum current draw. For example, the RWH-SH-105D relay requires around 70 mA in the "on" position. While this is under the 130mA limit, you may be using other IOs or powering other modules.

To reduce the current draw, use a transistor to drive the relay like this:


Problem with reading multiple potentiometer values on Arduino Uno I'm working on an Arduino sketch that will read in values from two potentiometers. The code for this is below:

int lastPotentiometerOneValue = 0;
int lastPotentiometerTwoValue = 0;

void setup() {
  // initialize serial communication at 57600 bits per second:
  Serial.begin(57600);
}

void loop() {
  delay(10);
  readAndSendPotentiometerDataIfChanged();
}

void readAndSendPotentiometerDataIfChanged(void) {

  //Potentiometer One
  int newPotentiometerOneValue = analogRead(A0) / 10.2;
  if (newPotentiometerOneValue == lastPotentiometerOneValue) return;

  Serial.print("!pos1");
  Serial.print(newPotentiometerOneValue);
  Serial.print(";");
  lastPotentiometerOneValue = newPotentiometerOneValue;

  //Potentiometer Two
  int newPotentiometerTwoValue = analogRead(A1) / 10;
  if (newPotentiometerTwoValue == lastPotentiometerTwoValue) return;

  Serial.print("!pos2");
  Serial.print(newPotentiometerTwoValue);
  Serial.print(";");
  lastPotentiometerTwoValue = newPotentiometerTwoValue;
}

The schematic for my circuit is below (I've left out the code for reading the state of the push-button in my listing above, as that's in a separate method from the method that reads in the potentiometer data):

However, there seems to be a rather subtle error I'm experiencing. If I turn Potentiometer One, it will display the correct output in the serial monitor. If I turn Potentiometer Two, no value will be displayed. However, if I remove Potentiometer Two from the circuit board and turn Potentiometer One, then the serial monitor will display the Potentiometer Two as having the same data as Potentiometer Two.

I'm sure the problem is with my circuit, but I'm not quite sure what I'm doing wrong. Does anyone have some insight? Thank you!

One problem is that if the value for pot1 has not changed, the value for pot2 will never be sent, even if it has changed, due to the early return when checking the value of pot1. You could fix this by changing to:

void readAndSendPotentiometerDataIfChanged(void) {

  //Potentiometer One
  int newPotentiometerOneValue = analogRead(A0) / 10.2;
  if (newPotentiometerOneValue != lastPotentiometerOneValue) {
      Serial.print("!pos1");
      Serial.print(newPotentiometerOneValue);
      Serial.print(";");
      lastPotentiometerOneValue = newPotentiometerOneValue;
  }

  //Potentiometer Two
  int newPotentiometerTwoValue = analogRead(A1) / 10.2;
  if (newPotentiometerTwoValue != lastPotentiometerTwoValue) {
      Serial.print("!pos2");
      Serial.print(newPotentiometerTwoValue);
      Serial.print(";");
      lastPotentiometerTwoValue = newPotentiometerTwoValue;
  }
}


library mixing log4Esp & Syslog for esp8266 has someone finaly made a new lib combining log4esp and syslog
cf :
SyslogAppender for log4esp
thanks:!

I did a rather dirty (but efficient for my purpose) job : While creating a new logger I declared and attached to it a log4esp formatter in which I sent ... syslog messages

dirty dirty dirty

my config constants are : SYSLOG_SERVER, SYSLOG_PORT, DEVICE_HOSTNAME, APP_NAME

My logger.h:

#ifndef Logging_H
#define Logging_H
#include <Log4Esp.h>
namespace Logging
{
void setup() ;
log4Esp::Logger Logger(const char *name);
}
#endif

my logger.cpp:

#include <Log4Esp.h>
#include <Syslog.h>
#include <WiFiUdp.h>
#include <ESP8266WiFi.h>
#include "Logger.h"
#include "config.h"
namespace Logging
{
// A UDP instance to let us send and receive packets over UDP
WiFiUDP udpClient;
// Create a new syslog instance with LOG_KERN facility
Syslog syslog(udpClient, SYSLOG_SERVER, SYSLOG_PORT, DEVICE_HOSTNAME, APP_NAME, LOG_KERN);
//new logger
log4Esp::Logger Logger(const char *name)
{
  //new instance
  log4Esp::Logger logger = log4Esp::Logger(name);
  //minimal level
  logger.addLevelToAll(log4Esp::Appender::LOG_LEVEL);
  // formatting for serial logging
  logger.addFormatterToAll([name](Print & output, log4Esp::Appender::Level level, const char *msg, va_list * args) {
    ////////////////////////////////////////
    // serial log format
    // output uptime of this program in milliseconds
    output.printf("%10d", millis());
    output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
    // output free heap space
    output.printf("(%d)", ESP.getFreeHeap());
    output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
    // output logger name
    output.printf("%-4s", name);
    output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
    // output log level
    output.print(log4Esp::Appender::toString(level, true));
    if (level <= log4Esp::Appender::Level::ERROR) {
      output.print("***");
    } else {
      output.print("   ");
    }
    output.print(log4Esp::Appender::DEFAULT_SEPARATOR);
    // determine buffer length for formatted data
    size_t length = vsnprintf(NULL, 0, msg, *args) + 1;
    char buffer[length];
    // output formatted data
    vsnprintf(buffer, length, msg, *args);
    output.print(buffer);
    ////////////////////////////////////////
    // Stop here if wifi is down
    if (WiFi.status() != WL_CONNECTED)
      return;
    ////////////////////////////////////////
    // format for syslog
    uint16_t slevel;
    switch (level) {
      case log4Esp::Appender::Level::FATAL    :
        slevel = LOG_CRIT;
        break;
      case log4Esp::Appender::Level::ERROR    :
        slevel = LOG_ERR;
        break;
      case log4Esp::Appender::Level::WARNING  :
        slevel = LOG_WARNING;
        break;
      case log4Esp::Appender::Level::VERBOSE  :
        slevel = LOG_INFO;
        break;
      case log4Esp::Appender::Level::TRACE    :
      default:
        slevel = LOG_DEBUG;
        break;
    }
    syslog.logf(slevel, "%10d|(%d)|%-4s|%s", millis(), ESP.getFreeHeap(), name, buffer);
  });
  return logger;
}
void setup() {

}
}


Are there any commonly available and supported backlit, monochrome graphic LCDs with more than 128x64 pixels? I am currently using a ST7565 graphic LCD for display in a heat pump system.

This LCD has the following characteristics:

128x64 pixels
2.5"x1.5"
monochrome, no greyscale
backlit
good viewing angles
serially connected (i.e. only uses a small number of pins)
high enough refresh rate to show animated icons
low cost (£20)
has a high-quality, maintained library
available from multiple sources for several years

I am finding the resolution of the screen limiting for my application. Ideally I would like a display that is exactly the same but with a higher resolution. Something between

I do not want:

colour (largely as the display is less visible, but also increased cost and code complexity), but red/green/blue on black would be OK.
a physically smaller display (all of the OLED displays are small - 2" and below) as it needs to be visible from a distance

Are there any displays that meet these requirements?

I hope that the specific requirements here mean that this is not a simple "shopping question".

Here you can find a bunch of displays at new haven display, which are big and OLED and not too expensive:

2.7" 128x64 OLED
3.12" 256x64 OLED

Those OLED Displays have a really excellent viewing angle and can be read from far (given you accept those sizes, which are >2").

Otherwise, the biggest I know about are LCD ones from NHD over there:

320x240 LCD with backlight

What's good with them, it's that they can cope with production in case this is needed, their prices are decent and their product just work(cTMr). You can find the u8g library to run them.


Will the Duemilanove bootloader work in the Uno? Similar to Will the Uno bootloader work in the Duemilanove? but the other way around.

I have an Arduino Uno. I require a slower upload speed than the 115200 baud rate used in the Uno's Optiboot bootloader.

The Arduino Duemilanove uses the ATmegaBOOT_168_atmega328 bootloader which has an upload baud rate of 57600. The Arduino Duemilanove also uses the ATMega328P like used on the Arduino Uno.

Will the Duemilanove bootloader work in the Uno?

Yes it will.

Both the Arduino Duemilanove and Arduino Uno use the ATMega328P microcontroller. (There is also a version of Arduino Duemilanove ATMega168 that uses the Diecimila bootloader and that is not compatible, so just watch out).

The main difference between the Arduino Duemilanove and the Arduino Uno is that the Duemilanove uses FTDI FT232R IC, whereas the Uno uses the Atmega8u2 microcontroller fto handle the USB to serial UART interface.

Also important is that both boards both have the same 16MHz clock rate.

The schematic for the Arduino Duemilanove can be found here.
The schematic for the Arduino Uno can be found here.

Of course, instead of selecting Arduino Uno as the board type, you need to always select Arduino Duemilanove or Diecimila and the ATmega328 processor.


multiple multiplexer (4051) - how to process the inputs? I have my Arduiono which has only a limited amount of Inputs/Outputs. But in my project I will have to attach a ton of potentiometers/buttons/LEDs, so I will have to use the IC4051-Multiplexer/Demultiplexer.

I have understood how to switch the Inputs/Outputs via the 3-Bits. But I don't get it, how to connect multiple ID4051s and process the signals(?)

Can someone explain that to me?

I have no experience of this chip but I would guess that you would need to connect the child level multiplexer to the output of the parent and use the outputs to drive the address lines.

You could look at an MCP23008 or MCP23016, these are 8 and 16 bit GPIO expanders that you control via I2C.  You can have 8 of the MCP230008 (64 pins) before you need to look at I2C bus expanders (which you can get).  I think its the same for the 16 bit version, but you would need to double check.


Can Arduino Mega ADK charge connected smartphone? I suppose Arduino Mega ADK acts as the USB host for the connected smartphone.

Is it capable of providing power to the smartphone?

If you read the documentation, you will see this paragraph:

  NB: Because the MEGA ADK is a USB Host, the phone will attempt to draw power from it when it needs to charge. When the ADK is powered over USB, 500mA total is available for the phone and board.The external power regulator can supply up to 1500mA. 750mA is available for the phone and MEGA ADK board. An additional 750mA is allocated for any actuators and sensors attached to the board. A power supply must be capable of providing 1.5A to use this much current.

So yes (though slowly), if you connect it to a suitable power supply.


Reading pressure sensor using Arduino analog I'm using a Arduino Uno to read pressure and I want to know if I have wired/coded the sensor correctly. I'm not sure I'm getting the correct readings (it could be the right readings - I just want to check I have done everything right). The sensor I am using is an OsiSense™ XMLP pressure sensor that reads between 0 and 100 bars and gives out a 0v (zero bars) to 10v (100 bars) charge. Due to the Arduino Uno only being capable of reading up to 5 volts, I've used a voltage divider to reduce the maximum voltage the Arduino receives to 5v.

I've attached a hand-written diagram. Let me know if you need any more information. I've attached the wiring and also the code.

/*
  ReadAnalogVoltage from a OsiSense XMLP presure sensor

  Reads an analog input on pin 0, converts it to voltage and then bar pressure, and prints the result to the Serial Monitor and also MQTT.
  Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).

  Todo
  Static ip. set it to request IP from network
  Work out best way to average readings

*/

#include <SPI.h>  //Serial Peripheral Interface (SPI)
#include <Ethernet.h>  //  These libraries are designed to work with the Arduino Ethernet Shield (Ethernet.h)
#include <PubSubClient.h>  // This library provides a client for doing simple publish/subscribe messaging with a server that supports MQTT

// sets the MAC address and IP address for the network
byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192,34,98,221);  // IP Address of the client
IPAddress server(192,34,98,201); // The IP address of the MQTT server

void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
}

EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);

void setup() {
  Serial.println("Begin setup");
  Ethernet.begin(mac, ip);
  // Note - the default maximum packet size is 128 bytes. If the
  // combined length of clientId, username and password exceed this,
  // you will need to increase the value of MQTT_MAX_PACKET_SIZE in
  // PubSubClient.h

  // connects to MQTT and says hello world.  Probably change this later on to something more appropriate
  if (client.connect("ArdRigTest")) {
    client.publish("outTopic","Ard Rig Test");
    client.subscribe("inTopic");
  }
  // start serial port
  Serial.begin(9600);
}

void loop() {
  // Note - the default maximum packet size is 128 bytes. If the
  // combined length of clientId, username and password exceed this,
  // you will need to increase the value of MQTT_MAX_PACKET_SIZE in
  // PubSubClient.h

  // read the input on analog pin 0:
  int sensorValue1 = analogRead(A0);
  delay(2); // read twice with small delay to get accurate reading.
  int sensorValue2 = analogRead(A0);

  Serial.println(sensorValue2);
  //Test code. using map function
  int MapBarPressure;
  MapBarPressure = map(sensorValue2, 0, 1023, 0, 100);
  if (client.connect("ArdRigTest" )) {
    client.publish("MapBarPressure",String(MapBarPressure).c_str());  //logs the pressure of the RigTest
    client.subscribe("MapBarPressure");
  }
  delay(100); // Pauses the program for the amount of time (in miliseconds) specified as parameter. (There are 1000 milliseconds in a second.)
  client.loop();
}

Thanks in advance.

You can use map, ref. : https://www.arduino.cc/en/Reference/Map

  Re-maps a number from one range to another. That is, a value of
  fromLow would get mapped to toLow, a value of fromHigh to toHigh,
  values in-between to values in-between, etc.


Implementing DES or AES Encryption with DateTime Synchronization on Uno We are trying to implement AES or DES encryption using an Arduino Uno.

We have a keypad module attached that will be used to input integers. A String should be generated based on the entered data and encrypted using AES or DES.

We have tried several online libraries with no success due to the constraints put on the "plain text" size.

An example pseudo-code for the above:

string key = "This is a key";
string plain = "This is the keypad input" + keypadInput + "and some other random stuff"; <- This should have any size.

var cipher = AES.encode(plain, key);
print(cipher);

var decoded = AES.decode(cipher, key);
print(decoded);

Could someone please point to the right direction on how to do this?

We have no experience with the byte[] objects and whatnot.

Might be time to do a few tutorials. You won't get far programming if you don't learn how to use arrays.

The string class is part of the STL (Standard Template Library) which does not come pre-installed on the Arduino (however you can download it if you want to).

The Standard Template Library (STL) for AVR with C++ streams

Briefly, however you could do something like this:

char key [20] = "This is a key";
char keypadInput [16];  // whatever they entered

char plain[80];

strcpy (plain, "This is the keypad input");
strcat (plain, keypadInput);
strcat (plain, "and some other random stuff");

The example code doesn't have any size checking. You would want to make sure that you don't put more than 79 characters into "plain" (to allow for the terminating 0x00 character). For example, look up strncat.

  Can you please elaborate on how DES or AES as described in the question can be implemented?

Have you done much research? Have you Googled Arduino AES encryption like I just did? I got this as the first hit:

Topic: new AES library - Arduino Forum

  I've written an AES (Advanced Encryption Standard) library for Arduino.  It supports 128, 192 and 256 bit key sizes.  Code space overhead is about 4KB I think, each instance requires 240 bytes RAM for subkeys.  Fairly tightly coded and checked against official test vectors for ECB mode.  Also CBC mode supported.

  It seems that if value of plain is larger than 16 characters the library will encrypt the first 16 characters only... Is this an Arduino Uno limitation?

I don't want to seem unhelpful, but you really should do some research before asking these questions. From Wikipedia - Advanced Encryption Standard (AES):

  AES is a variant of Rijndael which has a fixed block size of 128 bits, and a key size of 128, 192, or 256 bits.

A "fixed block size of 128 bits" means you encrypt 128 bits at a time, that is, 128/8 = 16 bytes.

So no, it is not an Arduino Uno limitation, it is the way AES works.

Also see Wikipedia - DES.

  In the case of DES, the block size is 64 bits.

So DES does 8 bytes at a time.

What you can do with a password is to hash it, for example: Secure Hash Algorithm or MD5 (amongst others). These algorithms take a variable length string and return a fixed "hash". In the case of MD5 the output is a 128-bit field.

You could then encrypt that 128-bit hash, if you want to keep it a secret.

  Would encrypting the 16 bytes and then append the next 16 bytes and so on result to the same output as if the whole plain text was encrypted in the first place in one go?

The suggestion by @BrettAM was, if you want to encrypt more than 16 bytes, do them 16 bytes at a time, padding if necessary the final block.

eg.

AAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBB CCCCCCCCCC000000
      encrypt        encrypt          encrypt
LLLLLLLLLLLLLLLL MMMMMMMMMMMMMMMM NNNNNNNNNNNNNNNN
      decrypt        decrypt          decrypt
AAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBB CCCCCCCCCC000000

In this example the final block was padded with zeros. Now the receiving end decrypts in 16-byte blocks.


How to get string parts from string? I have this method:

void getWeatherData() {
    String resp = "";

    Process p;
    p.begin("python2.7");
    p.addParameter("/root/weather.py");
    p.run();

    while (p.available() > 0) {
        char c = p.read();
        resp = resp + c;
    }

    Serial.print(resp);
    Serial.flush();
}

In the serial monitor, I see the string 70.7|45|1030.29|06:05|20:04|04 May 2015 22:24. The delimiter here is the pipe. Now, the parts I take a send them to methods that puts the values on the TFT screen.

However, I fail to understand how to split this long string into individual parts.

Can somebody help?

Thanks

EC

I used to have my own String class with a member method called Chomp which did exactly what you are requiring.  The body was something similar to this untested code:

String chomp(String& pSrc, char pMatch)
{
    int matchPos = pSrc.indexOf(pMatch);    // Find the first occurrence of the separator
    if (matchPos < 0)   // Separator was not found.
    {
        String ret = pSrc;  // Return the remainder of the source string.
        pSrc = "";          // Clear the source string
        return ret;
    }

    String ret = pSrc.substring(0, matchPos - 1);   // "Chomp" the start of the string up to the separator into the return value
    pSrc.remove(0, matchPos);                       // Remove everything up to and including the separator.
    return ret;
}

Hopefully the above code should be pretty understandable and fixable if there are any errors.  Our version worked on a "this" pointer rather than passing in the source string, so we would have something like:

String sourceCoords = "12,47,292,85";
int x1 = sourceCoords.chomp(",").toInt();
int y1 = sourceCoords.chomp(",").toInt();
int x2 = sourceCoords.chomp(",").toInt();
int y2 = sourceCoords.chomp(",").toInt();

Hope this is of some use.


Powering Peltier using solar panels I am a beginner to electronics and trying to make a portable air conditioner using a Peltier cooling pad (12V). I am planning on using a solar panel to power the Peltier and looking forward to your expert opinion  for below;
- Is this possible?
-What the specifications I have to consider prior to purchasing the solar panel?
- What is the weight of the solar panel?
- Can I operate the Peltier through an Arduino using Solar panel as the power source( without using batteries to power Arduino and Peltier). My idea is to control the Peltier cooler via Arduino using a phone App.
Really sorry if these questions are basic, yet your guidance will be very much helpful for me as well as for the other beginners like me.

Your first decision is to figure out the heat load on the space. How many BTU/hr you need to remove to keep the temperature you want. Then figure out how large / how many Peltier you need to remove that much heat. Do you need some reserve capacity for unusual circumstances or is a higher inside temperature Ok sometimes? Then you need a power budget - how much power will it take to remove that much heat with Peltier panels. How much PV area will you need to provide that power? If you need cooling when the sun isn't out, your power budget has to include the 24-hour demand, and the intermittent supply, perhaps again with some headroom. Power storage - batteries or the power grid - will be a requirement to match the two. The same storage can power your Arduino. The Arduino's power budget will be minuscule compared to the rest of the installation and you can totally ignore it. Do you have to power your internal network that connects the Arduino to the Internet, too? Figure that in. By this point, you'll have the answers to most of your questions. Just a heads-up: A Peltier beer-cooler is quite doable. A whole house A/C might be doable but no practical - you probably won't like the numbers! I'm guessing your project lies somewhere between the two.


Is a HC-SR04 fast enough to make decisions on moving robot (4 Johnson motors 300 rpm)? I am working on a project in which I have made a robot powered by 4 Johnson DC motors (300 rpm) and controlled by Arduino UNO R3. Now in my project I'd used ultrasonic sensor (HC-SR04) for detecting obstacles.

What I want is that as soon as my an obstacle is detected robot should turn by 180° but what actually happening is that sometimes robot takes turn very late (though I'd kept range of sensor approximately 50cm) and sometimes it just collides with obstacles.

As I'm new to Arduino I just want to know if an ultrasonic sensor is fast enough to sense obstacles and signal the Arduino about it, before it gets close enough?

Here's my code

int sense()
{
     analogWrite(trigPin, 0);
 // instead of digitalWrite(trigPin,LOW);
     delayMicroseconds(2);

/* as I'd used my digital pins for  motors and all i have to use pwm pin for  trigger pin of sensors i guess it doesn't make any difference*/

     analogWrite(trigPin, 255);
  // instead of digitalWrite(trigPin, HIGH);
     delayMicroseconds(10);

     analogWrite(trigPin, 0);
     duration = pulseIn(echoPin, HIGH);

     distance = duration/58.2;

      if (distance > maximumRange)
          return 0;
      else
          return 1;
}

On it's max speed, how far is it's braking distance?
Then you should start braking atleast from before that distance of the object.

Let's say your braking distance is 25cm, you should start braking >25cm.
But this is only when you would instantly brake at the moment you're within 25cm reach.

So we have to know how many distance we will travel during the calculation, before we start braking.
You could just try it out, set the distance a little higher everytime you crash into it (Assuming it doesn't fail and is always at the same time).

We have to know the top speed of your motor, RPM doesn't say a lot in this story, we'll need to know how big your wheels are to be able to determine how many cm's you'll travel per revolution, and doing that times the RPM, you know your top speed. (Or you can also measure this, but it can change depending on how full your battery is)

Also, your code should be real-time you'll likely want to use timers to trigger the trigPin and use an interrupt on the echoPin to be sure none of your code will delay your sensor. This will improve execution speed aswell as reliability/deterministic timing. Also, it will make it possible to run it aside from your regular code.

So if you know, your top speed = 10cm/second.

And you know that 1 calculation+reaction-time is 200ms.

You can safely assume that you need >2cm extra.

To be honest, you should add a little for when it's slippery/another surface or just so you won't touch the object.

So. The ping sensor is almost always fast enough, only if the calculated range is outside your max range, it will not work.
You could however, use an IR proximity sensor which will trigger at a set distance. This way you don't have to do any calculations and just brake whenever you receive the interrupt. But it won't tell you the distance to the object.

The cool thing on the distance sensor is that you can also scale the brake distance on your driving speed, so that it will brake later when you're driving on half your speed. That way you can come very close to an object, but still be 100% sure that you won't crash into it.


HC-05 bluetooth module not accepting AT commands I have been attempting to program my HC-05 ZS-040 Bluetooth module for quite some time, and I cannot get the AT commands to return any values. I have searched google for quite some time, and I none of the answers seem to work for me. I have been following along with this website:

https://sites.google.com/site/wayneholder/inexpensively-program-your-arduino-via-bluetooth

I am using an Arduino Mega 2560 clone by Elegoo to program this Bluetooth module. Currently I have it wired up using this diagram

https://sites.google.com/site/wayneholder/inexpensively-program-your-arduino-via-bluetooth/HC-05-to-FTDI.png?attredirects=0

Currently I have it modified slightly to use a voltage divider between the Arduino's Tx and the HC-05 Rx, as the HC-05 works on 3.3v logic. The one possibility I think could be causing this problem is that the Arduino Mega is just interpreting all Tx incorrectly as I measured that it sounds ardoun 3.2 volts for a high voltage. According to multiple websites the HC-05 is in AT command mode when the LED flashes slowly, about once every 2 seconds, which is happening. I put it in command mode by holding down the button above the EN pin while providing power to the HC-05.

I have been using pin 14 and 15, which are Hardware Serial3 on the Arduino Mega. Here is the code I have written:

  /*
  Software serial multple serial test

 Receives from the hardware serial, sends to software serial.
 Receives from software serial, sends to hardware serial.
 */
#include <SoftwareSerial.h>

SoftwareSerial mySerial(15, 14); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("AT");
  // set the data rate for the SoftwareSerial port
  Serial3.begin(38400);
}

void loop() { // run over and over
  if (Serial3.available()) {
    Serial.write(Serial3.read());
  }
  if (Serial.available()) {
    Serial3.write(Serial.read());
  }
}

Any suggestions are much appreciated!

EDIT:
I have now received some unrecognizable responses from the controller after sending AT multiple times, here is the screenshot, included is a video of my circuit, which shows how the LED is flashing:

https://drive.google.com/open?id=1mc8PEEnhiKpPzzy5kL9QxTvoQA3NAH6b

The only modification to the code is adding a Serial.println("TESTING"); in the while loop that reads Serial3. I have tried using other Hardware serial ports as well, all with the same result as the above screenshot.

###### Try This : Your Code Updated With Possible Fixes  ######

After examining your code and comparing it to my working code I believe I have found a definitive answer.  I'm altering your code so you can copy it and try it.  I'll add comments where I've changed it.

#include <SoftwareSerial.h>

SoftwareSerial mySerial(15, 14); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  Serial.println("Enter AT commands:"); // a prompt in Serial Monitor
  // Deleted while loop, unnecessary

  // set the data rate for the SoftwareSerial port
  // notice that your comment on previous line says SoftwareSerial port
  // but you are setting the Serial3 port -- this is where we use mySerial
  // Serial3.begin(38400); // commented your line of code
  mySerial.begin(38400);
}

void loop() { // run over and over
  //if (Serial3.available()) { // we don't use Serial3 any more
  if (mySerial.available()) {
    //Serial.write(Serial3.read());
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    //Serial3.write(Serial.read());
    mySerial.write(Serial.read());
  }
}

I am confident that if you use this newly modified code it will solve your problem.  I should've noticed this earlier.

Here's the rest of my original answer.

I have struggled with this myself.  As a matter of fact it took me a few months of owning some HC-05s before I finally dug up an answer.  It's been a while since I worked with it so I'll do my best to explain what to do.

Arduino Nano

Also, I use an Arduino Nano to do the programming of the HC-05.

This Setup Lets You Alter HC-05

Once you wire it up and run the program (included here) you will be able to send any of the HC-05 commands and they work great.  You can change the name of the device, the 4-digit pass-code and everything.

Crude Snapshot, But Enough To Build Simple Circuit

I also have a crude snapshot* of the circuit I used (at the time just for documenting it for my own memory) but I think we can work you thru it.  and I know those wires are all crammed together and it almost looks like they are in the same breadboardholes but they are actually hooked up properly.  I was so excited it finally worked I snapped the pic too fast.

*see image below

Here's the code I use:

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup()
{
  //pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  //digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);  // HC-05 default speed in AT command more
}

void loop()
{

  // Keep reading from HC-05 and send to Arduino Serial Monitor

  if (BTSerial.available())
    {
     //Serial.println("bt available...");
    Serial.write(BTSerial.read());
    }

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());
}

Does Your HC-05 Have the Button?

Okay, so the first thing is to check to see if your HC-05 has the little button on it?  If it does that has to be held when you apply power to the circuit.  The HC-05 will blink and then it will be in COMMAND mode and you can let go.

If No Button

You can see that mine has the button.  That is why the first two lines the setup() method are commented out.  I don't need D9 to go high (it is not connected to the pin) because mine has the button. If yours has the button (most likely does) then you don't even have to worry about it.

Looking Back At Your Question

Now that I look back at your sample code it could be that you're not aware that you have to hold that button when you power up.  Or you don't know that you need to connect that wire to keep the HC-05 in command mode.

Pins For TX / RX

That's probably the problem you are having, because everything else looks the same -- except you are using 15 and 14 for TX / RX.  I am using D10 and D11 for mine and I remember something about those pins in the back of my mind so if yours still doesn't work, try switching to those and try using my code.

I remember the first time I finally got this working and I was dancing around the room. Good luck and I hope you are dancing soon.  :)


MKR 1010 disconnects COM-port on each upload Each time I attempt to upload to the MKR WiFi 1010 board the COM-port gets disconnected, usually at one of the following points:

Either it disconnects just after compiling/verifying. In this case the LED_BUILTIN pulsates slowly, and the USB-cable needs to be reconnected in order to try again. The next attempt usually results in 2..

Or, it disconnects after a successful upload. The next attempt to upload will always result in 1. occurring. When this happens the COM-port is still visible in Windows Device Manager but it can't be found by a Serial Monitor.

Any ideas what could be causing this or what could be done to have it stay connected? With an UNO this doesn't happen.

This was due to using a virtual machine (VMware) which apparently doesn't handle the MKR board COM-port so well. Moving the development environment to the host solved the problem. It still disconnects the COM-port after upload but then consistently reconnects to the same COM-port and that's good enough.


Shock sensor is not running in the file I have faced an issue where the shock sensor is not running in the file. My idea is that when the ultrasonic sensor sense that when it is 4cm, the garage door will open. When the car reverses, the obstacle avoidance sensor will check if there is obstacle behind. These two sensors are working fine.

After that, shock sensor will be activated to see if the car has hit the wall.
But from shock sensor part onwards, the shock sensor does not run. I troubleshoot by putting the shock sensor code into another sketch and it works.

I have no idea where I have done wrong. I appreciate any help

Update
I have modified the code to accommadate interrupts which is advised by CodeGorilla. I need help with how can I let the interrupt know that they can execute when it reaches the if (distance == 4).

 #include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2); // set the LCD address to 0x27 for a 16 chars and 2 line display

const int trigPin = 9;
const int echoPin = 10;

long duration;
int distance;

const int shockPin = 3; // Use Pin 3 as Input

void setup() {

  Serial.begin(9600);

  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Distance left:");

  // Ultrasonic Sensor
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  // Obstacle Avoidance Sensor
  pinMode(8, INPUT);// set pin as input

  // Shock Sensor
  pinMode (shockPin, INPUT) ; // input from the KY-002

  attachInterrupt(digitalPinToInterrupt(3), detectShock, CHANGE);
  attachInterrupt(digitalPinToInterrupt(8), senseObstacle, CHANGE);
}

void detectShock ()
{
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Detection: ");
  if (digitalRead(shockPin) == LOW) // If we're in an alarm state
  {
    lcd.setCursor(0, 1);
    lcd.print("Shock exists");
  }
  else
  {
    lcd.setCursor(0, 1);
    lcd.print("Shock is absent");
  }
}

void senseObstacle() {
  lcd.clear();
  lcd.setCursor(0, 0);
  //delay(300);
  lcd.print("Detection:");
  if (digitalRead(8) == LOW) {
    lcd.setCursor(0, 1);
    lcd.print("Obstacle Present");
  } else {
    lcd.setCursor(0, 1);
    lcd.print("No Obstacle");
  }

void loop() {

  // Clears the trigPin
  digitalWrite(trigPin , LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin , LOW);

  // Reads the echoPin, returns the sound wave
  // travel time in microseconds
  duration = pulseIn( echoPin , HIGH);

  distance = duration * 0.034 / 2;

  lcd.setCursor(0, 0);
  lcd.print("Distance left: ");

  lcd.setCursor(0, 1);
  lcd.print(distance);
  lcd.print(" CM");

  if (distance == 4) {
    // I am lost at here.
    lcd.setCursor(0, 1);
    lcd.print("Door Opens");
    delay(500);
    // Once the car enters, the obstacle avoidance sensor checks if there are obstacles in the way..
    delay(5000);
    lcd.clear();
  }

}

}

I'm pretty certain that your code is the problem.  You are relying on timing rather than events.  Using delays is OK when you are just interfacing to one sensor but when you start mixing them you end up with issues like this.

You are reading the vibration sensor once every second if the distance is 4.  So any vibration needs to occur for more than one second, or at exactly the right time.  I think you need to look at a better way of coding the solution without using the big delay statements, maybe look at interrupts.


Combining 2 State Machines? I want to gain from recent advice from this forum by re-doing my project using 'state machine' logic if possible, in an effort to reduce wasted processor time and variables usage.

I'm starting from Nick Gammons 'state machine to process input from the serial port' example http://www.gammon.com.au/statemachine, which shows all the different possible combinations for all the special control character 'events' against all the possible machine states - essentially a 2-dimensional grid.

I've refined my goal to the processing of serial input in a format of "command  [parameters]  [options]", similar to a DOS command-line format, eg:  DIR  "c:\program files"  /w /s. This would free me from needing large Buffer[] and Header[] string, and avoides any parsing,

Therefore my event control characters are space, comma, single-quote, double-quote, forward-slash, Carraige Return, and my 'states' are NULL, COMMAND, PARAMETER, OPTIONS

The OPTIONS state adds characters to a temporary option[] string until a comma or space delimiter or Carraige Return causes that option to be processed as appropriate, perhaps saving its value to a recognised variable.

The COMMAND and PARAMETER 'states' add characters to their corresponding command[] and parameters[] strings, including the special control characters if they are contained within either single or double quotes (thereby allowing quotes as part of a string if used within a pair of the other type).

So there appears to be a second state machine needed for NoQuotes, SingleQuotes and DoubleQuotes to modify the operation of the COMMAND, PARAMETER and OPTIONS states.

This is where I run out of neurons, because all I see is an impossibly complex 2-machine-state 3-dimensional grid with too many possible permutations.

But I suspect there must be a very practical way to implement this, because it lies at the heart of almost all command-line utilities dating back to a time when processor power and memory availability were scarcer than hens teeth, and those old DOS command-line utilities needed to be as mimimal as was possible, including their command-line parsing.

So can anybody suggest a feasible model (machine-state or otherwise) for getting command-line type format from input?

UPDATE

Oh dear... I've just seen another complication I hadn't spotted before, which is that '/' options are not necessarily always at the end, which means that except if the options state changes by carraige-return, options state change by delimiter have to return to the state prior to the options state change (phew, I hope that makes some sense).  Anyway, I think it's back to drawing board because this approach seems likely to be too complicated, as the 2 answers already suggest.

Personally I don't think Nick advised to do command line pattern parsing with a state machine. His example is about changing a state machine based on command line input.
I have written some command line parsers and I never used a state machine to do so. I would not advice to use a state machine to do so.
Simple string parsing is far easier.

Edit To answer the remark below:
I would not advice to go byte by byte. I'd advice to go the line by line way.
I have written a library to do read line by line and an article on how that one works. http://blog.baeyens.it/#post16
Here a link to the lib https://github.com/jantje/libraries/tree/master/SerialCommunicator.
Here is a parcing code example. It is not so interesting for you as I have it done in a stage by stage way in a very high level way of coding.
https://github.com/jantje/libraries/blob/master/SerialBridgeCommunicator/SerialBridgeCommunicator.cpp#L21

Basically the algorithm is=
1 Take the first word;
2 identify the word.
3 If the command is complete ->do it
 else Send the rest of the string to a specialized piece of code. (which has the same algorithm)


Wire.h not found newliquidcrystal The arduino IDE can't seem to find the wire.h file when i'm using the new liquid crystal library. Does anyone know how to solve this? here is the code i'm using and the error message:

/*-----( Import needed libraries )-----*/
#include <Wire.h>  // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>

/*-----( Declare Constants )-----*/ /*-----( Declare objects )-----*/ // set the LCD address to 0x27 for a 16 chars 2 line display // A FEW use address 0x3F // Set the pins on the I2C chip used for LCD connections: //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

/*-----( Declare Variables )-----*/ //NONE

void setup()   /*----( SETUP: RUNS ONCE )----*/ {   Serial.begin(9600);  // Used to type in characters

  lcd.begin(16,2);   // initialize the lcd for 16 chars 2 lines, turn on backlight

// ------- Quick 3 blinks of backlight  -------------   for(int i = 0; i< 3; i++)   {
    lcd.backlight();
    delay(250);
    lcd.noBacklight();
    delay(250);   }   lcd.backlight(); // finish with backlight on

//-------- Write characters on the display ------------------ // NOTE: Cursor Position: (CHAR, LINE) start at 0     lcd.setCursor(0,0); //Start at character 4 on line 0   lcd.print("Hello, world!");   delay(1000);   lcd.setCursor(0,1);   lcd.print("HI!YourDuino.com");   delay(8000);

// Wait and then tell user they can start the Serial Monitor and type in characters to // Display. (Set Serial Monitor option to "No Line Ending")   lcd.clear();   lcd.setCursor(0,0); //Start at character 0 on line 0   lcd.print("Use Serial Mon");   lcd.setCursor(0,1);   lcd.print("Type to display");

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/ {   {
    // when characters arrive over the serial port...
    if (Serial.available()) {
      // wait a bit for the entire message to arrive
      delay(100);
      // clear the screen
      lcd.clear();
      // read all the available characters
      while (Serial.available() > 0) {
        // display each character to the LCD
        lcd.write(Serial.read());
      }
    }   }

}/* --(end main loop )-- */

Here is the compiler output

  Arduino: 1.6.7 (Windows 10), Board: "Arduino Nano, ATmega328"

  C:\Users\martin\Documents\Arduino\libraries\LiquidCrystal\I2CIO.cpp:35:26:
  fatal error: ../Wire/Wire.h: No such file or directory

  #include <../Wire/Wire.h>

                      ^

  compilation terminated.

  exit status 1 Error compiling.

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

The liquid crystal library has to be installed in the same folder as the wire library:

libraries/Wire/Wire.h (etc)
libraries/LiquidCrystal/LiquidCrystal_I2C.h (etc)

There is a hard-coded path in the liquid crystal library pointing to the wire library that is relative to where the liquid crystal library is, which is done to get around the problem that the Arduino library doesn't recurse libraries. It's not actually needed since including the Wire library in the IDE is enough to tell it where to find it for the liquid crystal library, so I don't really know why they did it that way.


Uno as a composite USB HID keyboard I'm looking to create a USB device that would  be basically a HID keyboard. I am able to do that with Uno. I flash new firmware with a HID keyboard descriptor and on the arduino side I loop and check for button presses. Based on butotn presses I send the report.

What I would like to add to this is option to send some data from a PC and based on that data do something (like turn an LED on.)

Here is an example:

loop() {
  check_and_send_buttons();
  uint8_t inputByte = get_input(); //new
  handle_input(inputByte); //new
}

I'm on Linux and I tried sending some data via hidrawX but that did not work out.
Any ideas?

I'm willing to also write new device driver for Linux if needed.

On UNO R3 the HID protocol is handled by the secondary AVR present on the board. Which is the one talking to the PC. So what you should modify is the code implementing the USB protocol on the secondary AVR.

The main (328p) AVR interacts with it through the serial port.

You do not need to alter the Linux driver, since it already supports the driving of the usual LEDs (CAPS, Num Lock, Scroll Lock), if these are enough for you.

So, to recap:

1) enhance the HID implementation to understand LED status commands coming from the PC

2) report such changes over serial

3) on the primary AVR, monitor for such messages coming over serial port from the secondary AVR and use them to drive the LEDs.


Test level shifter with Arduino and some data Below is a reference to a logical level bi-directional converter (aka level shifter) I purchased on Ebay.  I've soldered the 12 pins (6 for each piece) to the level shifter so that it fits on my bread board.

http://www.ebay.com/itm/121868205078?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

This may sound trivial, but I'd like to troubleshoot the level shifter with communication both ways (Rx and Tx) to make sure it's working properly.  I've got a constant 4.85v (5V) going to the HV pin, and a constant regulated 3.24V (3.3V) going to the LV pin, along with ground to both GND pins.  Right now, I'm using pin0 (Rx) and pin1 (Tx) on the Arduino Mega 2560.

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

void loop() {
  delay(1000);
  Serial.println("Test");
}

How can I test this level shifter without any fancy components?  How could I write a program to toggle an LED both on LV1 and HV1 pins, by modifying the program above?  Please note, that even though the Arduino runs on 5V, I am not using the Arduino as my HV power source.

EDIT (per comment 3 by @Paul):

Test:

Burn blank sketch into Arduino
Connect 5V (Arduino 5V) to HV pin
Connect GND (Arduino GND) to GND pin on same side as HV pin
Connect 3.3V to LV pin
Connect GND (from 3.3V power source) to GND pin on same side as LV
pin
Connect Arduino Tx pin to channel 1 (HV1)
Connect Arduino Rx pin to channel 2 (HV2)
Short channel 1 to channel 2 with jumper wire

When all of this is connected, and I open the Serial Monitor on Arduino IDE, anything I type will echo back exactly what I typed.  And when I disconnect one of these jumpers, it doesn't echo back.  So it seems to work.

You don't need to write any program.

First, note that this is (or at least purports to be) an I2C level shifter. This means that it does not actively pull up anything; it only actively pulls down. You are supposed to provide pull-ups somewhere in your circuit.

To test it, pull up HV1 and LV1 with 10K resistors to HV and LV respectively; measure the voltage on both sides to verify you are pulling to ~5V and ~3.3V respectively.

Ground HV1, check that LV1 is low.

Ground LV1, check that HV1 is low.

Ta-dah!


Connecting 5V arduino logic with 12V car logic I need to connect arduino to K-Line in my car's OBDII port.
I used an L7805 to power the atmega but how can I interface 12V car logic with 5V arduino logic?
The problem is, the connection has to be bidirectional- sometimes the arduino will pull the line high/low and sometimes the car will - the purpose of this connection is to get throttle, rpm etc. data.
This would be easy if the connection was one directional - I could use a transistor to steer 12V to going IN the K-Line and voltage divider if I wanted to do the reverse. But how to do both?

I found this that may be helpful to you.  this circuit allows for bidirectional communication between automotive K-line ECUs and an arduino.
 K-Line Interface circuit