LM35 temperature decreases when heated I have a question regarding the LM35. The sensor is supposed to have values that are to be directly proportional. But instead of the temperature increasing, the sensor values decrease.
This is my setup below. It seems to be a standard setup in different LM35 tutorial pages.

const int sensor= A0; // Assigning analog pin A0 to variable 'sensor'

void setup() {
  pinMode(sensor,INPUT); // Configuring sensor pin as input
  Serial.begin(9600);
}

void loop() {

  float reading=analogRead(sensor); //Reading the value from sensor
  float vout= (reading*5000)/1024;
  float temp= vout/10;

  Serial.print("in DegreeC= ");
  Serial.print(temp);
  Serial.println("");

  delay(500); //Delay of 1 second for ease of viewing

}

These are the results. From room temperature, I applied heat through the use of a lighter and it went lower instead of higher.

I read somewhere that it has something to do with the power supplied by the Arduino. However, when I used a 12V supply to power the Arduino, the readings became very erratic and unstable.
UPDATE:
I have finally returned from the city (Took a long time because of Quarantine Restrictions) and I brought 3 LM35 from another shop. All 3 of the new LM35 worked as intended and didn't lower its temp reading when exposed to heat (With the same configuration). I could rule out these possibilities as to the reason why the LM35 didn't work.
1. Manufacturing Defect - all three of the LM35 didn't work as intended. They all had their temperature lowered when exposed to heat. There could be a defect in the manufacturing process because it doesn't work as advertised. (Leaning towards this)
2. Static Electricity - I remember receiving the LM35 in a plastic bag as packaged by the shop. It could have been affected by static electricity and damaged the circuit inside (on all three though?). The LM35s I received recently had been packaged in those electrostatic discharge protection packaging so it could have probably contributed to it? I need more insight on this I apologize for not being able to properly word it out.
There could be more but these are the most I could come up with as a conclusion.

You are reading A5 but in your diagram you show it hooked up to A0:

Change your code to this and I believe it will work:
const int sensor= A0; // Assigning analog pin A0 to variable 'sensor'

void setup() {
  pinMode(sensor,INPUT); // Configuring sensor pin as input
  Serial.begin(9600);
}

void loop() {

  float reading=analogRead(sensor); //Reading the value from sensor
  float vout= (reading*5000)/1024;
  float temp= vout/10;

  Serial.print("in DegreeC= ");
  Serial.print(temp);
  Serial.println("");

  delay(500); //Delay of 1 second for ease of viewing

}

The data you are reading from A5 is indeterminate and just happens to decrease as A0 increases.
================================================================================
UPDATE:
Ok, so you corrected yourself and are reading the correct pin in spite of what your schematic shows.  Please explain this:
float vout= (reading*5000)/1024;
float temp= vout/10;

I think you want:
float vout = (reading/1024.0) * 5000.0;
float temp = vout/10.0;

You are carelessly mixing floating point and integer math.


Playing WAV file from Arduino Uno using Ethernet R3 Shield I'm trying to start a project where I have a 6 sec recording (wav file: 8 bit, 8 or 16 kHz, mono) on a micro-SD card and want to play it through my Arduino Uno on an 8 Ohm, 0.1 W speaker. I've looked at many different forums and threads for how to do this. One that continually comes up is this link, but this is for the Due and I can't figure out how to adapt for the Uno.

The important bit is I am using an Ethernet R3 shield which has a built in micro-SD card reader. Much of the code and tutorials I found use the TMRpcm library, setting the speaker pin to 9, the SDChipSelectPin to 4, with various wire connection geometries depending on which tutorial you read. I really need help trying to figure out how the wiring is supposed to go. I, honestly, do not understand what's going on and am hoping someone will take the time and can explain this pretty pedagogically. Currently, no matter what I try, I just hear high-pitched static or fast periodic noises.

Your Arduino UNO won't play any wave file the way you're expecting. There's not enough processing power to do that.
In order to play audio using small MCUs such as AVR (or PIC for example) you must use the BTC algorithm. Please, check this out : http://www.radanpro.com/Radan2400/mikrokontroleri/How%20to%20make%20sound%20with%20a%20PIC%20chip.htm
and download the software which can convert your wave file into an array which can be then played by Arduino using a BTC algorithm. Schematics on how to place reistors and speakers to match impedance are provided and suggested on the software as well.


Fast Python to arduino communications I've been communicating with a teensy arduino over USB using pySerial--which has been simple, but slow. With simple write commands from Python and a corresponding read command on the teensy, I can only achieve 200kHz transfer rates. I'm hoping to get over 1MHz at least, but I don't see a path towards that rate.

Are Ethernet shields capable of augmenting for rates over the MHz range? How can I get faster data transfer rates between my computer and arduino? I'm mainly interested in one-way communications (computer directs teensy).

The fastest means of communicating with the Arduino is SPI. Ethernet shields use that (as do SD cards). It's quite fast, but it has limits. The fastest the SPI clock can go is the CPU (MCU) clock rate divided by 2 (per bit), that is one byte every 16 CPU clock cycles. There is also an overhead of a couple of clock cycles between bytes, so you can reckon on 888,888 bytes absolute maximum (ie. about 868 kHz) on an Arduino running at 16 MHz.

However that's just throwing the data away. It needs to be stored somewhere, compared to something, acted upon. That all takes clock cycles.

That is for the 16 MHz Arduinos. The Teensy 3.1 apparently runs at 72 MHz which is somewhat faster. I haven't timed SPI on that, presumably you can get a faster transmission rate, but I suspect that the ARM processors also take more instructions to do the same thing, so the 72 MHz might not be quite as fast as it looks.

Then you have the issue of how fast you can get data in and out of the Ethernet card, and how fast you can do whatever-it-is you want to do with it, in the processor.


half duplex for Atmel SAMD21 I'm using Arduino MKR GSM 1400. I know this board uses Atmel SAMD21 and SAMD21 support half duplex (USART with full-duplex and single-wire half-duplex configuration). My question is, How Can I configure one of the SERCOMs to use it as Half-Duplex (Use one pin for rx and tx)?

Up to six Serial Communication Interfaces (SERCOM), each configurable
to operate as either:

USART with full-duplex and single-wire half-duplex configuration
I2C up to 3.4 MHz
SPI
LIN slave

It is an error in the overview of the SAM D21 features in the datasheet. The SERCOM is half-duplex for I2C. USART can't be configured half-duplex.
see Application Note about SERCOM configuration

1 Introduction to Serial Communication Interfaces (USART, I2C, and
SPI)
... The exchange of data can be half-duplex or fullduplex depending on
the serial module specification. ...
1.1 USART
... It is full-duplex in operation. ...
1.2 I2C
... It is half-duplex in communication. ...


Move a servo slowly between 2 positions based on input I am trying to move model railroad crossing gates from a vertical position to a horizontal position when a train is detected. I have the electronics in for the sensing of train position but want the gates to go down and stay down while the train passed.

To do this, I am looking to be able to use an Arduino to slowly move a servo between two different positions based on a digital input (HIGH or LOW) to one of the digital input pins.

When this digital input goes HIGH, the servo needs to slowly move to the other end of travel and then stop. It must stay there until the digital input goes LOW, at which time it needs to slowly move back to the starting position and again await for a HIGH input.

I cannot figure out how to move the servo slowly to each position and keep it there.

Lacking information about the context of the servo action (ie, what needs to happen at the same time), I'll assume your paradigm uses a loop() function that executes fairly rapidly, and from time to time invokes any necessary actions.

Servo angles can be measured in degrees (typically 0 to 180) or microseconds (typically 1000 to 2000, corresponding to 0° to 180°).  The servo library will accept numbers in either range, and act according to which range the numbers are in.  Note that representing servo angles in microseconds instead of degrees gives about 5.55 times better resolution.  The method outlined below doesn't care which you use.

Also assume the two servo angles mentioned in the question are A and B, with the servo at A if the input pin is low for a long time; and that the desired rate of swing is ±U units of angle every S milliseconds.  Let P = current servo position; T = millis() value at most recent step, initially 0; and V = previous value of input pin.

In each pass through loop():

• Test the input pin.  If it isn't equal to V, toggle V and take a step.  (See below.).
• If  millis()-T > S, take a step.  (See below.)
• Do any other brief per-loop actions

To take a step:
• Add (2*(V>0)-1) * U to P.  The expression (V>0) equals 1 or 0, so (2*(V>0)-1) is 1 if V is true, and -1 if V is false.
• If (V) and P > B, set P = B
• If (!V) and P < A, set P = A
• Servo to position P
• Set T = millis()

Edit: You should create meaningful variable or constant names to represent the quantities A, B, P, S, T, U, V.  Note that S and T should be declared as constants; and if A, B won't change, make them constants also.  State-maintaining quantities P and T should be declared via file-scope variables or globals (outside loop()) or with static allocation (inside loop()), so that their values are maintained as main() repeatedly calls loop().


What is the relation between Arduino's clock and possible VGA resolution? I have seen it said over and over (in different places) that in order to achieve 640x480 resolution out to a DB15 VGA connection, the arduino would need to be clocked at 25Mhz or that at half resolution it would need to be clocked at 12.5Mhz.

What is the relation between resolution and internal clock? I would expect that so long we can feed the signal fast enough that would be enough.

I doubt if that would be fast enough. See my thread about connecting to a VGA monitor.

Borrowing from that page, so as to not make a link-only answer ...

For 640x480 pixels of active video you have something like this:

Vertical Sync

Let's start with the vertical sync pulses. In fact, we'll show how all the timing data can be derived from three figures:

The screen refresh rate (eg. 60 Hz)
The screen resolution (eg. 640 x 480)

So what is the refresh rate? It's the rate at which the entire screen is redrawn. If you ever looked at Windows screen resolution you probably saw something like this:

That's the refresh rate: 60 Hz (60 times a second). This figure was probably originally chosen because it is the mains frequency in the USA, so that would minimize the artifact of mains hum bars appearing on the screen, in the days of CRT monitors.

The other figure of interest is the screen resolution.

In our case we are going for the minimum we can (640 x 480) and seeing where those figures lead us.

Starting with the refresh rate, a 60 Hz refresh rate will require a "vertical sync" pulse 60 times a second, or a period of 1/60 (16.66 ms).

Generating vertical sync pulses

This code in my VGA output sketch generates the vertical sync pulses:

  // Timer 1 - vertical sync pulses
  pinMode (vSyncPin, OUTPUT);
  Timer1::setMode (15, Timer1::PRESCALE_1024, Timer1::CLEAR_B_ON_COMPARE);
  OCR1A = 259;  // 16666 / 64 uS = 260 (less one)
  OCR1B = 0;    // 64 / 64 uS = 1 (less one)

The clock period is 62.5 ns (1/16000000). By applying a prescaler of 1024 the timer counts up once every 64 µs. So to get a period of 1/60 of a second (16666 µs) we need to count up to 260 (16666 / 64 = 260). Since the timer counts are zero-relative we set OCR1A to count up to 259. This sets the frequency of Timer 1.

Then we need to set the pulse width by putting the correct value in OCR1B. We want a pulse width of two lines. One line is 1 / 60 / 525, namely 31.7 µs. So two lines would be 63.4 µs. This is close enough to exactly one timer count (64 µs). So OCR1B is set to zero (being zero-relative, making it zero gives a count of 1).

Timer 1 is configured to "clear B on compare" which effectively means that it toggles the output pin (D10 on the Uno) so it is high for the duty cycle width (64 µs) and low the rest of the time. If you wanted the opposite sync pulse polarity, change CLEAR_B_ON_COMPARE to SET_B_ON_COMPARE.

The timer is also set up to generate an interrupt, which is used to tell the code that we are starting another vertical cycle, by setting the line count to zero:

ISR (TIMER1_OVF_vect)
  {
  vLine = 0;
  messageLine = 0;
  backPorchLinesToGo = verticalBackPorchLines;
  } // end of TIMER1_OVF_vect

Horizontal sync

Horizontal sync pulses tell the monitor when to start drawing each line.

To calculate the horizontal sync frequency we need to divide the overall frame rate (60 Hz) by the number of total lines (525 if you count the sync pulse itself, and the front and back porches).

In other words:

 (1/60) / 525 * 1e6 = 31.74 µs

We also need to know the sync pulse width. That is documented to be 96 pixels, so we need to know the width of one pixel. That would be the figure above, divided by 800 (being the total screen width including the sync pulse, and front and back porches).

Thus that is:

((1/60) / 525 * 1e9) / 800 = 39.68  ns
1 / (((1/60) / 525 * 1e6) / 800) = 25.2 MHz

So our pixel width is 39.68 ns and the pixel clock is 25.2 mHz.

The horizontal sync pulse width is 96 pixels, so we want a pulse of:

96 * 39.68 ns = 3.8 µs

Generating horizontal sync pulses

Now we are ready to set up the timer for the horizontal sync pulses:

  // Timer 2 - horizontal sync pulses
  pinMode (hSyncPin, OUTPUT);
  Timer2::setMode (7, Timer2::PRESCALE_8, Timer2::CLEAR_B_ON_COMPARE);
  OCR2A = 63;   // 32 / 0.5 µs = 64 (less one)
  OCR2B = 7;    // 4 / 0.5 µs = 8 (less one)

The clock period is 62.5 ns (1/16000000). By applying a prescaler of 8 the timer counts up once every 0.5 µs. So to get a period of 32 µs we need to count up to 64 (32 / 0.5 = 64). Since the timer counts are zero-relative we set OCR2A to count up to 63. This sets the frequency of Timer 2.

Then we need to set the pulse width by putting the correct value in OCR2B. We want a pulse width of 96 pixels (3.8 µs). So OCR2B is set to 7 (being zero-relative, making it 7 gives a count of 8, which is 4 / 0.5).

Again, if you wanted the opposite sync pulse polarity, change CLEAR_B_ON_COMPARE to SET_B_ON_COMPARE.

The timer is also set up to generate an interrupt, which has the sole purpose of waking the processor up from sleep, so it can draw each line with exactly the same delay after the pulse. If it wasn't asleep, there would be a variation of two to three clock cycles (since an interrupt cannot occur during a single instruction) and this gives very bad-looking "jitter" on the screen.

ISR (TIMER2_OVF_vect)
  {
  } // end of TIMER2_OVF_vect

Pixel data

Now things get tricky ...

Let's see how long we have to draw 640 pixels:

((1/60) / 525 * 1e9) / 800  * 640 = 25396.82 ns (25.39 µs)

It just can't be done on this processor. The clock period itself is only 62.5 ns, so there is no way we can output a pixel every 39.68 ns (that is: 25396.82 / 640 = 39.68).

The fastest way we can get bits "out the door" is using the SPI hardware. That can run at a maximum clock rate of twice the system clock, that is, one pixel every 125 ns. So we will have to settle for having the pixels 4 times as wide. A horizontal resolution therefore of 160 pixels. Since we will display 8-pixel characters, that gives us 20 characters per line.

Summary

Even at 25 MHz processor speed (which exceeds its spec) you won't be able to clock out pixels fast enough for 640 pixel width (since the fastest SPI speed is half the processor clock speed).

  I would expect that so long we can feed the signal fast enough that would be enough.

That's the tricky bit. To output data you have to do more than merely send it. You have to read it from memory, so it would take a least a couple of clock cycles to do that.

Example of working at that resolution

A screen shot of my sketch in action (160 characters wide - 640 pixels and 30 characters high - 480 pixels, which is 16 pixels each as they were "doubled" in height to make them look in proportion). The font data was 8x8 pixels, and thus they appear as 16x16 on the screen.

  So does that mean that there really isn't a direct relation between clock speed and resolution? Other than, the clock must be faster than this

To work even at that speed the processor speed needs to be a multiple of the VGA clock, or close enough for the monitor to accept. (Looking at my figures the pixel rate is not in fact a multiple of 39.68 ns, so I am guessing that my monitor was able to adjust).

You could get better results by having a system clock which was an exact multiple of 39.68 ns (around 25 MHz - precisely 25.201613 MHz) - which is what you suggested in the question. However that just gives more accurate timing, you would still get similar resolution to what I show here.

So yes, to work on more monitors you should have a direct relation between clock speed and resolution.

I seem to have a 25.175 MHz crystal in my parts drawer, so perhaps I experimented with this a while back. Of course, you have to recalculate the other timings if you use that, and the processor is running out of spec.


How do i power recycle on SD card I am working on my home made project where i am using SD card to log GPS data into it,As well as i have to access that data from the SD card on my computer while all the system is connected to battery power, so i also have a USB to SD chip USB2240 from Microchip, this SD controller suits best to my application, Because USB2240 has a card detect pin connected to one of the pin of Arduino, from which i can control interface of SD card between Arduino for logging and the computer for the USB..

But I have to Recycle power to the SD card whenever SD Card is interfaced with the USB controller USB2240.

So for an Example : when the device is powered 'ON' , The SD card is interfaced with the Arduino - which logs data to the card, But when i connected the system to my computer to get the logged file on my computer, Then it's not working, Here i have to disconnect power to SD card and Reconnect it...

How do i achieve Power recycle all on it's own when i connected to the USB OR to the Arduino.

Thanks

I just read the

USB2240 Part listing

and it looks really handy for interfacing a PC to the flash.

However, I believe you are taking the wrong approach by trying to power recycle it yourself.

To address your question about how to power recycle it:  If you are physically moving the connection cable then that should power recycle it automatically.

If not, then you have some other problem with your software not tolerating the disappearance then reappearance of the SD card.  In other works, it is likely a software problem.  The SD card should always remain connected so the software does not get confused and require a reset.

It is like how you need to eject USB devices in Linux.  If you don't, then you can get file corruption because the buffers may not be fully flushed.  Back in the day we used sync; sync; sync to ensure buffers were written out to storage devices, even just to do a normal shutdown.  Fortunately, modern Linux takes care of that, with the exception of USB flash memory.  With that you need to actually go through the eject process to avoid damage or system confusion.

But a much better approach would be to just leave it on one or the other.
Then use some sort of communications (it doesn't have to be USB) between the two computers for memory access.


How do I reduce this down to a smaller, more permanent prototype? I've prototyped a little light/sunrise alarm clock w/ an Arduino Uno and a breadboard. How do I go about figuring out what components I'd need to reduce this down in to a more semi-permanent prototype?

Obviously I don't need everything the Uno has to offer and I'd like to slim this down into a custom box I build.

But what sort of microcontroller(s) would I need to size this down? How else can I simplify it?

To be clear, I'm not trying to turn this in to any sort of finished/super-polished product. Just wanting to get out of the breadboard and in to some soldering of something a bit more set in stone.

At a bare minimum, you need a power supply, and an AtMega or AtTiny chip.

The AtMega and AtTiny's have an internal clock, 1mhz. It's not terribly accurate for timekeeping purposes (1% error, I think, as opposed to 20ppm = 0.02% for the external clock), but I see you have an RTC, so a 1% drift is probably fine (I can't see your code, so I don't know if the internal time is used for anything). Remember that you will need to adjust your code for the different clock rate, anything that uses anything time-related will run at 1/16th speed (delay, serial comms, etc). You will need to set the fuses to use the internal clock.

If your power source isn't 5v, then you need a transformer.

What type of AtTiny or AtMega you use depends on your code, and how many pins you use. I see 5 pins, they are all used as digital I think? You might get away with one of the 14-pin AtTinys. I suspect your code is probably pretty small. You can probably get away with nearly any AtTiny. To select an AtTiny, go to http://www.atmel.com/products/microcontrollers/avr/tinyavr.aspx

Nick Gammon (who will probably be providing his own answer as I type) has an excellent site on how to put the parts together, at http://www.gammon.com.au/breadboard

This site mentions programming the bootloader. On a low-memory chip, you do not need a bootloader, you can upload your program using SPI (same way as you upload the bootloader in Nick's example). Alternatively, you can use a programmer like the USBASP, which makes the whole process a lot easier. When you build your final board, I strongly suggest putting a 6-pin ICSP header (same as the 2x3 pins on the end of your Arduino board) on, to make reprogramming easier. You plug the USBASP into the 6-pin header, and click File->Upload using programmer.

ADDITIONAL:

If you want your project "really nice", you can design and etch your own PCB. If "good enough is good enough" (which for me it always is), I suggest you use stripboard (also known by it's brandname, veroboard).

In either case, spend some time thinking about your exact layout. Use a computer layout tool, and spend some time working out the best layout. I generally spend at least 5 times as much time on the layout, as I do on building the board - if a project is twice as big, I will spend twice as much time soldering, but at least 4 times as long laying it out.


Code hangs with SPI, and OLED labraries (Possible conflict between Adafruit SSD1306 and hardware SPI libraries) I have an issue with using two libraries together, namely SPI.h that is installed together with an Arduino and Adafruit_SSD1306.h. My code was getting stuck so I stripped it down to the bare minimum to find where the problem occurs. Here's the stripped down code:
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>

//Screen Resoluttion
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_Res A3
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_Res);

#define _ssPin  7

void setup()   {
  pinMode(OLED_Res, OUTPUT);
  pinMode(_ssPin, OUTPUT);
  Serial.begin(19200);
  Serial.println("Serial set up");
  SPI.begin();
  Serial.println("SPI set up");
  Wire.begin();
  Serial.println("I2C set up");
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  Serial.println("Screen set up");
}

void loop()
{
  Serial.println("Loop entered");
}

I am debugging the code using serial monitor. The code as it stands right now hangs after I2C initialization. If I uncomment either SPI.begin() or display.begin(...) it jumps into the loop. Which leads me to think there might be a conflict between the two libraries. Which is weird considering I haven't found a similar issue on the internet and I doubt these two libraries are rarely used.

I used the same code provided by you and uploaded it in the arduino uno and it was working fine for me. I am attaching the image for reference. I guess there might be some other issue


65 hall effect sensors as switches to be used as a keyboard with a teensy I'm trying to wire up a silly little keyboard using hall effect sensors and magnets in a glove. The idea being only I can use the keyboard since I'll have the glove.

The sensors are 3 pin, (vcc, gnd, and an output that sends 5v out when a magnetic field is present. I don't have anywhere near enough pins on the teensy for all the sensors. Could I just use several port expanders? Are there issues with using 4 or 5 at once? How many keys could be pressed at a time?

Is there a better option than all those expanders?

Also I know that this keyboard will be ugly and completely impractible to use regularly, but I thought it would fun to show off.

[Completely rewritten answer]
That seems fun. But why 65 keys ? with 64 keys it is easier.

You have to test the sensitivity of the hall switches with the magnets to know how far apart the keys must be. Perhaps they only work with strong magnets or perhaps a number of them are activated when the glove is near.

With hall switches, there are 65 digital signals from the sensors.
The most common way to create more digital inputs is to use shift registers. For example with the 74HC165. Nick Gammon has the best tutorial of the 74HC165 with daisy-chain.
There is also an example is with the CD4021 and the ShiftIn function, but the 74HC165 is mostly used.
The shift registers can be daisy-chained, they are made for that.

Your AH1807 has a open-drain output. That means you need 65 pullup resistors.
It is not possible to connect all the outputs and turn them on one by one, since it requires 150ms to wake up.

Another option is using multiplexers. It can be used for analog and for digital signals. For example with four 16-to-1 multiplexers you can create 64 inputs going to 4 pins. The best multiplexer tutorial is once again written by Nick Gammon.

With four analog multiplexers of 16-to-1 you would require only 4 pullup resistors after the multiplexer. I think it is better to use a resistor per hall sensor (65 pullup resistors).

When using reed switches (those tiny glass tubes, used in house alarms), they can be set in a matrix/grid with rows and columns and the Keypad library. For example 10*7 requires 17 pins. The Keypad library allows that multiple keys are pressed at the same time.


How can i get rid of the error "cannot convert 'String' to 'const char*'" I want to get this code to recognise different commands and be able to parse the rest of the command, fore example I send "/sleep 5", and it will sleep for 5 seconds. However, I keep on getting this error "cannot convert 'String' to 'const char*'". here is my code:

#define maxCommandLength 64

String commands[] = {"/test", "/say", "/reset", "/sleep"};

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Power on.");
}
char serial[maxCommandLength];
boolean valid;
void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("Clearing command buffer(char 'serial'");
  for (byte i = 0; i < maxCommandLength; i++) {//if maxCommandLength is larger that 255, change 'byte i' to 'int i'
    serial[i] = ' ';
  }
  if (Serial.available()) {
    Serial.readBytesUntil(' ', serial, maxCommandLength);
  }
  if (serial[0] == '/') { //if it is a command
    Serial.print("Command recieved. \nCommand class:");
    Serial.println(serial);
    //test if command is valid
    for (byte i = 0; i < maxCommandLength; i++) {//if maxCommandLength is larger that 255, change 'byte i' to 'int i'
      valid = strcmp(serial,commands[i]);
      if(valid){
        break;
      }
    }
    //execution of command
    Serial.readBytesUntil(' ', serial, maxCommandLength);
    //.......
  }
}

there is no reason for command to be a String array. Instead make it a const char**:

const char** commands = {"/test", "/say", "/reset", "/sleep"};


Can AccelStepper accelerate non-linearly? I am running a Nema 23 motor with an Arduino Uno and a microstepper driver. I am making a torsional vibration demo, which uses a series of springs connected to the motor driveshaft to spin gears. These gears, as changes in shaft speed occur, should begin to weave in- and out-of-phase with one another. In my particular case, I am using three potentiometers, which read 0-1023, to read speed, amplitude, and frequency.
The changes in motor speed are where I run into my issues. I need the speed of the stepper to be a sinusoidal function - of the form "Speed - Amplitude x sin(frequency x time)".
Below is some rudimentary code I put together with the AccelStepper library, which does not work:
#include <AccelStepper.h>

/* Using a stepper motor,
  rotate a vibrational model using gears interconnected by springs
  in such a way as to induce torsional vibration, which should be visible by comparing
  movement of juxtaposed rotating gears with markers painted on. */

AccelStepper stepper(AccelStepper::DRIVER);
void setEnablePin(int enablePin = 8);

int Microstepping = 8; /* Microstepping factor, as set on the ST-M5045 control board.
                          Multiplies the number of steps per revolution on the stepper motor.
                          Reference controller manual for adjustments to this number. */
int Steps = 200; /* Number of steps on your stepper motor.*/
int SPS;
int Amp;
int Freq;
// int SC;
int n = 2;
int i;
int totalSteps = Microstepping * Steps;
int currentPosition();

/* It should be noted that the Microstepping and Steps factors are not necessary, and adjusting the microstepping factor
    on the fly will not break the code. However, be aware that changing the microstepping factor by more than one interval
    at a time can cause the motor to not keep up with the sudden changes, i.e. losing torque or vibrating/stuttering. */

void setup() {               // THIS RUNS ONCE //

  Serial.begin(9600);

  // read potentiometers; raw inputs from 0 to 1023 //
  SPS = analogRead(0) * 0.5; // MAX steps per second should be <1000. Speeds above 1000 unreliable, according to AccelStepper docs.//
  Amp = analogRead(1) / 20;   // MAX AMP ~51//
  Freq = analogRead(2) / 170; // MAX FREQ ~12 Hz//

  stepper.setMaxSpeed(1000);
  stepper.setAcceleration(SPS / 1.5);

  int nextStop = totalSteps / Freq;

  stepper.moveTo(nextStop);
  stepper.run();
  Serial.println("INITIALIZED");
}

void loop() {
  SPS = analogRead(0) * 0.95;
  Amp = analogRead(1) / 20;
  Freq = analogRead(2) / 170;

  float spd = SPS + (Amp*sin(Freq*millis()));
  stepper.setSpeed(spd);
  stepper.run();
  Serial.print("speed:  ");
  Serial.println(spd);
}

The issue I am having with the above code is that it enters the loop but does not vary the speed, despite the serial output showing me a speed which oscillates about the desired value several times a second.
And now, folks, what you've all been waiting for: The Point.
Does AccelStepper actually support non-linear accelerations not as the result of an error? I cite the following excerpt from the AccelStepper documentation,
 /// Sets the maximum permitted speed. The run() function will accelerate
 /// up to the speed set by this function.
 /// Caution: the maximum speed achievable depends on your processor and clock speed.
 /// The default maxSpeed is 1.0 steps per second.
 /// \param[in] speed The desired maximum speed in steps per second. Must
 /// be > 0. Caution: Speeds that exceed the maximum speed supported by the processor may
 /// Result in non-linear accelerations and decelerations.
 void    setMaxSpeed(float speed);

which makes the only mention of non-linear acceleration in all of the documentation - in the context of an overflow error.
I've thought of possibly using a modified version of the easydriver example program from reply #3 to this post if AccelStepper isn't capable of doing what I need it to do. Included is also an image of the system (minus the arduino and controller).
Thanks for your help in advance

I appreciate the votes for exposure! Here is the answer I got from Mike, the creator of AccelStepper himself: link
Short answer: no!
I've posted the program I'm using now, which accelerates nonlinearly using pulse timing variation, in the linked thread.
Happy stepping!


EthernetClient not initializing properly I am trying to make a connection with the EthernetClient, but it always fails with code 0. I decided to write a small code just to test if the client ever becomes ready, and as I suspected it does not.

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {0x2A, 0x27, 0x55, 0x08, 0x1E, 0x6A};
IPAddress ip(172, 16, 48, 133);
EthernetClient client;

void setup() {
  Ethernet.init(10);
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
  while (!Serial) {;}

  for (auto link = Ethernet.linkStatus(); link != LinkON; link = Ethernet.linkStatus()) {;}
  Serial.println("Link ON");

  while(!client){
    Serial.println("Client not ready");
    delay(1000);
  }

  Serial.println("Client ready!");
}

void loop() {}

If I try to run the code above, it gets stuck at the "Client not ready" loop, and I can't figure it out what I'm missing for it to work.

Obs.: I have already configured a web server with success with my shield, so I'm guessing the problem is not with it.

An EthernetClient expects to connect to a remote socket. At no point do you instruct it to connect to a socket, so it never succeeds.

At some point before checking for a connection you need to initiate that connection:

// arduino.cc is 100.24.172.113
IPAddress server(100, 24, 172, 113);
client.connect(server, 80);

The if (client) operation relies on sockindex having been assigned a valid value, and that is only ever done either by EthernetClient::connect() or by being explicitly set by EthernetServer::available().


Can a stepper motor be controlled directly from an Arduino? I'm planning to build a simple XY plotter, and have been looking at the possibility of using a pair of small 5V 4-phase steppers to provide the movement. In my research, I've often seen stepper driver boards advertised, ranging from very big and expensive, through to quite small and cheap. Some of them actually look like little more than a darlington array on a PCB.

Do I really need one of those external driver boards, or can I control the steppers directly from my Arduino?

Generally, stepper motors cannot be controlled by an Arduino pin. They have a current draw of over the 20mA any single pin can supply.

Kickback is also a problem. Because the motors have moving magnetic parts inside, they will continue to generate electricity after power has been cut. this will almost certainly cause enough negative voltage that is enough to fry your Arduino.

A solution is to use a motor driver chip or shield. This one is a good example. These have transistor based chips that can drive enough current to power a motor, and diodes to mitigate the kickback from the motors.


SIM808 module: GSM location command (AT+CIPGSMLOC=1,1) giving wrong value after execution of sending message command (AT+CMGS=+91xxxxxxxx) I wrote the code that if an interrupt is generated, get GSM location and send a  message.

The first time the interrupt is generated, I got the correct GSM location using AT+CIPGSMLOC=1,1 and successfully sent a message using the AT+CMGS=+91xxxxxxxxcommand.

But the next time an interrupt was generated, AT+CIPGSMLOC=1,1 gave a wrong location. When I commented out the code to send a message, on every interrupt generated I am getting the correct GSM location. So it seems like the problem is occurring after sending a message. But I have no clue what exactly is going wrong. Following is my code.

Note: on restarting the module, I'm again getting the correct location the first time, before sending a message.

void setup() {
  mySerial.begin(9600);
  Serial.begin(9600);
  while (!Serial) {
  }
  // initialize the pushbutton pin as an input:
  pinMode(sensorPin, INPUT);
  // Attach an interrupt to the ISR vector
  attachInterrupt(0, pin_ISR, FALLING);
}

/////////***GSM RESPONSE***///////////
String DisplayGSMResponse() {
  if(mySerial.available()) {
    String gsm_input="";
    while(mySerial.available()) {
      gsm_input+= (char)mySerial.read();
    }
    gsm_input.trim();
    delay(1000);
    Serial.println(gsm_input);
    return gsm_input;
  }
}

void SendMessage(String mobNum,String Location) {
  Serial.println("Sending message..");
  mySerial.println("AT+CMGF=1");
  //Sets the GSM Module in Text Mode
  delay(2000);
  // Delay of 1000 milli seconds or 1 second
  DisplayGSMResponse();
  mySerial.println("AT+CMGS=\""+mobNum+"\"\r");
  // mobile Number
  delay(4000);
  DisplayGSMResponse();
  cleanBuffer();
  mySerial.print("test");
  // The SMS text you want to send
  delay(100);
  mySerial.println((char)26);
  // ASCII code of CTRL+Z
  delay(8000);
  DisplayGSMResponse();
}

void gprsInit() {
  if (isGPRSInit) {
    return;
  }
  Serial.println("GPRS INITIALIZING");
  mySerial.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
  delay(2000);
  DisplayGSMResponse();
  mySerial.println("AT+SAPBR=3,1,\"APN\",\"INTERNET\"");
  delay(2000);
  DisplayGSMResponse();
  mySerial.println("AT+SAPBR=1,1");
  delay(8000);
  DisplayGSMResponse();
  mySerial.println("AT+SAPBR=2,1");
  delay(2000);
  DisplayGSMResponse();
  isGPRSInit = true;
}

void gprsterm() {
  mySerial.println("AT+SAPBR=0,1");
  delay(1000);
  DisplayGSMResponse();
  isGPRSInit = false;
}

String getGPS() {
  Serial.println("GETTING GPS LOCATION");
  String loc = "";
  String location = "";
  mySerial.println("AT+CIPGSMLOC=1,1");
  delay(3000);
  loc = DisplayGSMResponse();
  return location;
}

void loop() {
  if (buttonState == 1) {
    detachInterrupt(0);
    gprsInit();
    location = getGPS();
    SendMessage(mobileNumber, location);
    gprsterm();
    Serial.println("location = " + location);
    buttonState = 0;
    location = "";
    attachInterrupt(0, pin_ISR, FALLING );
  }
}

void pin_ISR() {
  buttonState = 1;
  Serial.println("interrupt");
}

EDIT: added gprsterm function.

Note: I removed the interrupt and called the code inside the loop function twice. The first time I got a correct result. The second time a wrong result. So it seems like the interrupt is not be causing the problem.

EDIT2:
One interesting thing I found is that at my home it is showing correct results every time, but in the office it is showing a wrong location on second location call i.e after the SMS was sent and we get the GSM location using AT+CIPGSMLOC=1,1.

It might be due to the command giving the nearest cell tower location. And for sending SMS it might be shifting to a different cell tower depending on your network. This could maybe be easily checked using a different cell provider or as you said its working at your home so I believe I am correct in assuming this is the answer


How to get text to flash on ssd1306 i2c screen I am trying to alternate a string back and forth on the SSD1306 oled screen.
So I want the display to show "test1" for 0.5 seconds, then "test2" for 0.5 seconds, repeating. the code below is just showing "test1" for 0.5 seconds then going blank...
I am using a ssd1306 128_32 i2c screen, and using the adafruit library.

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

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

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

  // Show initial display buffer contents on the screen --
  // the library initializes this with an Adafruit splash screen.
  display.display();
  delay(2000); // Pause for 2 seconds

  // Clear the buffer
  display.clearDisplay();

  // Show the display buffer on the screen. You MUST call display() after
  // drawing commands to make them visible on screen!
  display.display();
  delay(2000);

  display.setTextSize(4);             // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);

}

void loop() {
 testdrawstyles1();
 testdrawstyles2();
}

void testdrawstyles1(void) {
 display.clearDisplay();
 display.print(F("test1"));
 display.display();
 delay(500);
}

void testdrawstyles2(void) {
 display.clearDisplay();
 display.print(F("test2"));
 display.display();
 delay(500);
}

As approved by the OP, the error was caused by not having reset the cursor to a visible position on the display. The text was written outside of the OLED.

It seems as the clearDisplay() method does not reset the cursor.

The solution is to change the following methods

void testdrawstyles1(void)
{
  display.clearDisplay();
  display.setCursor(0,0);
  display.print(F("test1"));
  display.display();
  delay(500);
}

void testdrawstyles2(void)
{
  display.clearDisplay();
  display.setCursor(0,0);
  display.print(F("test2"));
  display.display();
  delay(500);
}


AVR timer overflow interrupt not working My problem is an interrupt service routine (ISR) that seemingly never executes! Here's some info on my set up: I am flashing an avr attiny85. I have the bare bones of a project set up so far with simply a main.c and two modules: timer and hardwareInit. In the timer module, I have a timer0_init function that I am using to set up timer0 for CTC mode to overflow ever 1 ms. Here is the function:

void timer0_init( void )
{
    cli();
    TCCR0B |= 3;    //clock select is divided by 64.
    TCCR0A |= 2;    //sets mode to CTC
    OCR0A = 0x7C;   //sets TOP to 124 so the timer will overflow every 1 ms.
    TIMSK |= 2;     //Enable overflow interrupt
    sei();          //enable global interrupts
}

with the timer set up, I added an ISR to increment ticks every time the counter overflows, so I can keep track of how much time has elapsed, etc.

ISR(TIMER0_OVF_vect)
{
    cli();
    //ticks ++;
    PORTB |= ( 1 << PORTB0 );
    sei();
}

as you can see, I commented out the ticks++ because it wasn't working, and replaced it with PORTB |= ( 1 << PORTB0 ); which simply turns on an LED, so if the interrupt is ever executed, I will know by proof of the LED being on.
Unfortunately, I can't get it to turn on and can't see what I'm missing. (to prove that I 1. have the LED set up on the right pin, and 2. am manipulating the correct bit in the correct register, I put just this statement PORTB |= ( 1 << PORTB0 ); in my infinite loop and confirmed the LED came on)

For further explanation, here is my main.c:

/*================================= main.c =================================*/

#define F_CPU   8000000UL

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

#include "timer.h"
#include "hardwareInit.h"

int main(){

    //Initialize hardware HERE
    DDRB |= ( 1 << PORTB0 );    //set this pin as an output for an LED

    SetClockPrescale(1);    //internal clock divided by 1 = 8 MHz, from hardwareInit

    timer0_init();          //set up timer0 for 1 ms overflow

    while(1)
    {
        /* if( getTicks() > 0 )
        {
            PORTB |= ( 1 << PORTB0 );
            _delay_ms(1000);
            PORTB &= ~( 1 << PORTB0 );
            _delay_ms(1000);
        } */

    }
    return 0;
}

So, what you see in the infinite loop is what I tried first, but after that didn't work, I tried something simpler, just having an empty loop (commented out previous stuff), and waiting for the interrupt to get triggered which would turn on the LED.

Any help you could give would be really appreciated. I'm quite puzzled why this hasn't been working.

You are misunderstanding what an overflow interrupt is. That is called when the timer overflows (ie. it reaches TOP which in the case of an 8-bit timer is 255). Since you are counting to 124 that will never happen, and thus the interrupt will not fire.

You want the "compare A vector" which is called when the "A" register compares to the limit. Example code:

void timer0_init( void )
{
    TCCR0B = bit (CS01) | bit (CS00);    //clock select is divided by 64.
    TCCR0A = bit (WGM01);     //sets mode to CTC
    OCR0A = 0x7C;             //what to count to
    TIMSK = bit (OCIE0A);     //Enable compare match A interrupt
}

ISR(TIMER0_COMPA_vect)
{
    PINB = bit (PINB0);   // toggle pin 5
}

int main(){

    DDRB |= bit (DDB0);    //set this pin as an output for an LED
    timer0_init();         //set up timer0 for 1 ms overflow
    sei ();                // allow interrupts
    while(true) { }        // forever
    return 0;
}

I changed it to toggle pin 5 (which happens extremely quickly) so it will seem to be on but a bit dim. You can see on an oscilloscope or logic analyzer that it is toggling rapidly.

You don't need to turn interrupts off or on inside an ISR. You are better off using the bit names rather than "magic numbers" in your code, as my example shows.


Transistor Switching I'm hoping that someone will be able to help me. I'm looking to produce a power interrupt for testing. I'm looking to have 28V DC input flowing to an output which I can hook up to a load and then switch on and off using an Arduino. I'm thinking of using an NPN high current transistor, I have built the box and code which runs fine. The issue I am having is the pin output on pin 13 doesn't have enough current to switch the transistor, can anyone recommend a transistor that would be able to take the high current and be switched by the Arduino? If you would like a schematic to help you understand it I can provide one!

Thanks for reading,
Lewis

If you did manage to switch the transistor on, It would only output 4.3V, the rest would be dissipated in the transistor. If you managed to switch 4A this would dissipate 96W - and the transistor would melt.

A MOSFET would be a better option and could be easily switched by the Arduino. (I regularly switch 10A using a MOSFET and Arduino.)

This assumes you can put the MOSFET in the negative lead. If not you should use a P-Channel MOSFET, but you need a more complex circuit to drive it.

Have you considered using a relay module?


FTDI Programmer 5v vs 3.3v for ESP8266 Context

I currently have a Sonoff S20 plug that is acting up and needs to be reflashed. (Over the air updates arent working)
The S20 plug is based on an ESP8266 chip.

Reading the documentation it states that you need a FTDI serial programmer @ 3.3v to get it done.
Instructions below

https://github.com/arendst/Sonoff-Tasmota/wiki/Hardware-Preparation

I am looking at this programmer here

http://www.ebay.com.au/itm/FTDI-FT232RL-USB-to-TTL-Serial-Converter-Adapter-5V-and-3-3V-For-Arduino-RZ/371993408316?epid=4004086862&hash=item569c88f33c:g:tdkAAOSw5VFWMM31

Question

The ebay item states its 3.3v AND 5v, I cant see two pinouts that supply different voltages.  If I was going to power this from my PC USB port is this thing going to output 5v and damage the ESP?
How am I supposed to get 3.3V out while connected to my PC?

I found a better picture that shows the jumper from above. I can see now that there is a jumper to toggle between 5V and 3.3V

http://buyhere22.com/components/usb-ttl-ft232rl-pinout.png


Keep RTC time in a loop I recently started a project with HC-SR04 sensors and RTC DS1302 clock. The idea is when a sensor detects an object, call and keep a timestamp (hh:mm:ss) all over the loop until Else If{} appears,  but I don't know how to.

#include <DS1302.h>
#include <Time.h>
#include <TimeLib.h>
#define echoPin 12 // Echo Pin
#define trigPin 13 // Trigger Pin

time_t t = now();
DS1302 rtc(6,20,21);
String inTime;

void setup()
{
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop(){
    long duration, distance;
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;

   if (distance <= 4) {
    inTime= rtc.getTimeStr();
    Serial.println(inTime);

    }

    else if (distance >= 5 || distance <= 0){
    Serial.println("Out of range");

    }

  delay(500);
}

Appreciate any help, thanks.

Check '{' and '}' pairs in your code.

void loop(){
    long duration, distance;
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;
    if (distance <= 4) {
        inTime= rtc.getTimeStr();
        Serial.println(inTime);

   }
} //<--- what is this little fella doing here?
    else if (distance >= 5 || distance <= 0){
    Serial.println("Out of range");
    }

delay(500);
}


Connect 9 V battery to Arduino Mega 2560 directly? Is it safe to connect a 9 volt battery to an Arduino Mega 2560 directly to power it?

Yes. On this page, you can see that you can safely connect 7-12V to the VIN pin.

Furthermore, you can simultaneously connect the USB; your Arduino will automatically draw power from the appropriate source.

Note that the power supply jack pin is connected to the Vin pin through a diode. Do not connect a battery and an external power supply, since a sufficiently high power supply voltage will try to charge your battery, which may be bad news for the battery.


Arduino reads hc-05 device connecting status Hello I want to get an arduino get status of bluetooth hc 05 if connect with device or not . I'm trying by myself and search on internet website but I can't find useful things.

In hc05 there is led that shows you Bluetooth is paired or not. In datasheet it says that connected the PIO9 pin. You can connect this pin to arduino's digitial input pin. After that you can understand is it paired or not.

AT+BIND? gives you which device you currently paired.


Arduino Uno to Arduino Uno Word.doc file transfer I have written a 2 sets of code for the transmitter and receiver section. I am trying to send a word document file from 1 arduino uno to the next arduino uno through serial TX and RX. The file is initially loaded into a micro sd card module at the transmitter section. I would like to transfer that file to the receiver section's sd card module. I am able to receive an empty word document at the receiver section. There is no information in the document. I would like some help with this. I will attach the transmitter and receiver code below.

Transmitter code:

#include <SD.h>
#include <SPI.h>

File fileIn;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
   while (!Serial){
    ; //  wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");
  if(!SD.begin(4)){
    Serial.println(F("Initialization failed!"));
    return;
  }
  Serial.println("Initialization done.");
  if(!SD.exists("student.txt")){
    fileIn = SD.open("student.txt", FILE_WRITE);
    fileIn.println(F("abc.txt"));
  }
  fileIn = SD.open("student.txt", FILE_READ);

  while(fileIn.available()){
    Serial.write(fileIn);
  }
  delay(1000);
  fileIn.close();
}

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

}

Receiver code:

#include <SD.h>
#include <SPI.h>

File fileOut;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial){
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");
  if(!SD.begin(4)){
    Serial.println(F("Initialization failed!"));
    return;
  }
  Serial.println("Initialization done.");
  if(SD.exists("student2.txt")){
    SD.remove("student2.txt");
  }
  fileOut = SD.open("student2.txt", FILE_WRITE);

  while(fileOut.available()){
    Serial.write(fileOut);
  }
  delay(1000);
  fileOut.close();
  Serial.println("It worked!");
}

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

}

while(fileOut.available()){
    Serial.write(fileOut);
  }

This doesn't quite do what you think it does.

Instead you should send the file length first and then do:

for(unsigned long size = 0; i< fileLength; i++){
    Serial.write(fileOut.read());
}

You should also investigate some kind of rate limiting to avoid overwhelming the reciever and having to drop some bytes.


Arduino I2C via USB Serial cable? An Arduino UNO is given.
I want to establish an I2C communication channel between Arduino UNO and a Linux Machine which have only USB ports available to communicate with peripherals.
Currently I can communicate with Arduino board via USB Serial cable (TXD and RXD which are on pins D0 and D1).

My question is: is there any way to use those pins as SCL/SDA to communicate via I2C with Arduino Board?

I am thinking that the only way to accomplish this is to buy an USB to I2C Adapter and connect to A4 (SDA) and A5 (SCL); but maybe I'm wrong.

I have also seen that way: https://gist.github.com/kraftb/8c0bbcc35a9778608d74. Basically to use an intermediate Arduino board.

With SoftwareI2CLibrary you can specify other pins, I haven't tested it with RX and TX.

I would recommend the USB serial interface is fast (2M baud) in perspective to that we are discussing a Arduino with a speed of 16MHz.


Why voltage at AREF is given by Vin * R2 / Rtotal In chapter 4 of Arduino Workshop on page 85 (or page 31 in the pdf) it says that the voltage at AREF in the schematic is given by:

Vin * R2 / (R2 + R1)

However, the voltage is flowing from 5V to Ground so isn't AREF actually in parallel with R1, and so shouldn't AREF be given by:

Vin * R1 / (R1 + R2) ?

You are correct.

$$V_{ref} = \dfrac{R_1}{R_1 + R_2} \cdot V_{CC}$$

or Vref = Vin * R1 / (R1 + R2) until we finally get MathJax enabled on this site.


Strange behavior on bitwise operation i am trying to write a simple program that writes the outputs of an accelerometer (which comes down to 3 analog inputs) onto an SD-Card.

I got the hole thing working fine (sending the values as simple strings), however i wanted to increase the frequency at wich the data is taken and therefore tried to send the data to the SD card encoded in binary, and therefore i am doing some bitwise manipulation.

Unfortunately some (as i think) strange things happen. When i add a simple bitwise manipulation the data on the SD card is pretty messed up. (I was unable to detect a pattern but it seems some Bytes are missing or or are there twice without any regularity):

Here is an example of a working version:

// Get raw accelerometer data for each axis
unsigned int rawX = analogRead(A0);
unsigned int rawY = analogRead(A1);
unsigned int rawZ = analogRead(A2);

byte b1 = (byte) (rawX>>2);
byte b2 = (byte) (rawY>>4);
b2 = b2 + (byte) (rawX<<6);
byte b3 = (byte) (rawZ>>6);
b3 = b3 + (byte) (rawY<<4);
byte b4 = (byte) (rawZ);
b4 = (byte)b4*4;
//b4 = (byte)b4<<2;

// get pressure
//temp = BMP180_getTemp();
//float a = 0;
//float a = pressure.altitude(BMP180_getPressure(), baseline);

unsigned long t = millis();

byte writeB[] ={
    b1,
    b2,
    (byte) (rawZ>>6), //replacing this with '(byte) ((rawZ>>6)|(0b11110000 & rawY))' will cause the error
//also replacing with b3 creates the error as well
    b4,
    (byte) (t>>16),
    (byte) (t>>8),
    (byte)t, (byte)0};

dataFile.write(writeB,8);

dataFile.flush();

As mentioned as a comment in the code changing the way the byte is calculated messes up my data on the SD card. I tried several other things however it seems that the following operations are causing the error: | & << >>  (However i am using some of them to calculate e.g. b2)

What i don't get is how changing how a byte is calculated affect the data output.

Maybe (probably) i overlooked some easy mistake but i cant figure out what is happening. Any help would be greatly appreciated since im working on this since quite a while.

(I am aware that the program does currently not transmit all necessary data but i startet from scratch and programmed step by step to locate/identify the error)

Your way of sharing the bits between the three values seems a bit confusing. Your code for saving the bits is correct in the meaning of that you save all relevant information. Your bytes are shared in this way (H means high portion of value, L is the low portion of value):

     ____HX_____
b1: | 0000 0000 |
     _LX_ ___HY___
b2: | 00 | 000000 |
     __HZ__ __LY__
b3: | 0000 | 0000 |
     __LZ____
b4: | 000000 | XX |

This is a rather complex way of dividing the space. Also, since you are not using the remaining 2 bits of b4 you don't have to shift there.

When you are getting garbled values from your SD card, it wildly depends on how you are reading the bytes (you haven't shown us the code for that). As a suggestion I will explain how I would do it.

We have 3 values from analogRead(), which each have 10 bits. So in total we have 30 bits, which can be transmitted in 4 bytes (or 32 bits). When adding bits from another value, I think you can use the + operator (opposing to my comment) if the bits of the different values don't overlay (which should be anyway). For my part I like to use the bitwise or | to show more clearly, what is done there and to easier check for errors in alignment (easy to see in binary representation). Do as you like. I will use the | operator for now.

// Get raw accelerometer data for each axis
unsigned int rawX = analogRead(A0);
unsigned int rawY = analogRead(A1);
unsigned int rawZ = analogRead(A2);

byte b1 = rawX & 0xFF;
byte b2 = rawY & 0xFF;
byte b3 = rawZ & 0xFF;
byte b4 = (rawX & 0x0300) >> 2
          | (rawY & 0x0300) >> 4
          | (rawZ & 0x0300) >> 6;

The low portion of the values are saved in the bytes b1 to b3. The upper 2 bits of every value is saved left-aligned to b4 (The & 0x0300 isolates the upper portion, bit 9 and 10, in the values.).

You can read these values in this way:

rawX = b1 | (( b4 & 0b11000000) << 2);
rawY = b2 | (( b4 & 0b00110000) << 4);
rawZ = b3 | (( b4 & 0b00001100) << 6);

b1 to b3 are the start for our retrieved raw values. Then we add the other 2 bits to the raw values. For this we first isolate the bits from b4 from the positions we used in the upper code. Then we shift them to the left, until they are directly above the 8 bits of the start values.


How to upload an arduino sketch from java / processing? I'm trying to upload a hex file from Java/Processing but running into some issues.
Here is my code so far, based on the Arduino IDE's upload verbose output:

void setup(){
    //C:\Program Files (x86)\Arduino/hardware/tools/avr/bin/avrdude -CC:\Program Files (x86)\Arduino/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328p -carduino -PCOM96 -b115200 -D -Uflash:w:C:\Users\HM\AppData\Local\Temp\build5909267154049588263.tmp/sketch_aug13a.cpp.hex:i
    String ArduinoPath = "C:\\Program Files (x86)\\Arduino";
    String hexPath = "C:\\Users\\HM\\AppData\\Local\\Temp\\build1023547366107161384.tmp/sketch_aug13a.cpp.hex";
    String port = "COM96";
    runCommand(new String[]{ArduinoPath+"/hardware/tools/avr/bin/avrdude", "-C"+ArduinoPath+"/hardware/tools/avr/etc/avrdude.conf","-v","-v","-v","-v","-patmega328p","-carduino","-P"+port,"-b115200","-D","-Uflash:w:"+hexPath+":i"});
  }
  void runCommand(String[] cmd){

    String s = null;

    try {

      Process p = Runtime.getRuntime().exec(cmd);
      BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
      BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

      // read the output from the command
      System.out.println("command out:\n");
      while ( (s = stdInput.readLine ()) != null) System.out.println(s);
      System.out.println("errors (if any):\n");
      while ( (s = stdError.readLine ()) != null) System.out.println(s);

    }catch (IOException e) {
      System.out.println("something went wrong: \n");
      e.printStackTrace();
    }

  }

If I run this from command line it uploads without any issues, but from the code above I always get this output:

avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardw
are\tools\avr\etc\avrdude.conf"

         Using Port                    : COM96
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "\\.\COM96": Access is denied.

avrdude done.  Thank you.

I'd first would try to find out the right command when running on command line (cmd.exe).

When you launch an external command from Java which generates output, you should/must read the output (p.getInputStream(), p.getErrorStream()) using separate threads. Otherwise your application might hang for no obvious reason.


Can the Arduino interface with a fingerprint sensor on my mobile? I own a OnePlus 6 and it has a fingerprint sensor. Instead of using a fingerprint scanner module like the R305, could I just use my mobile for scanning the fingerprints? If yes, how do I implement this?

This is for creating a smart home security system.

You'd need an app on your mobile to read the sensor and communicate the result to your Arduino in a secure way that cannot be spoofed by an intruder. That secure communication over an open channel (WiFi, I assume?) is not trivial to do right, so that would be a weak point in your security.

Blynk, an app+server+Arduino library combination provides an authentication token to pair with your Arduino in a relatively secure way. You quickly make (drag-and-drop) a control panel for your Arduino system with it. It doesn't offer fingerprint sensing directly, but if you keep your Blynk authentication token a secret, keep your Blynk app+token on your mobile, and the mobile is fingerprint-locked, you'd have essentially the same thing, and the pieces already exist. You'd only need to code the smart-home parts for the Arduino.


More effecient datalogging code Background:
I am using a Teensy 3.6 to data log over a dozen sensors. I am printing to Serial1 for local Serial access, Serial3 for remote access (via xbee, same data is on Serial1 as on Serail3, just different physical connection) as well as datalog to SDCard (CSV format). My code is expanding and is incredibly repetitive, and I am looking for a more efficient way of writing the following. I am trying to move a lot of the rest of my code to classes using this and this tutorial, but I'm not sure this is the best option for the datalogging as there are many more strings in this portion.
The variables we are dealing with:

Live sensor value (eOilTempF)
A visual flag for if the sensor is out of bounds (checkEngine)
A auditory alarm if it's further out of bounds (eOilTempAlarm)
The max value we've recorded (engineOilStats.maximum())
The minimum value (engineOilStats.minimum())

As well as all the little bits to make it attractive and human readable for the Serial stuff.
Code:
Local serial:
Serial.print("Engine Oil Temp:\t");
Serial.print(eOilTempF);
Serial.print("F\t   ");
Serial.print("Flag: ");
Serial.print(checkEngine);
Serial.print("\t Alarm:");
Serial.print(eOilTempAlarm);
Serial.print("\tMAX: ");
Serial.print(engineOilStats.maximum());
Serial.print(" F");
Serial.print("\t\t\t\tAVG: ");
Serial.print(engineOilStats.average());
Serial.println(" F");

Xbee serial:
Serial3.print("Engine Oil Temp:\t");
Serial3.print(eOilTempF);
Serial3.print("F\t   ");
Serial3.print("Flag: ");
Serial3.print(checkEngine);
Serial3.print("\t Alarm:");
Serial3.print(eOilTempAlarm);
Serial3.print("\tMAX: ");
Serial3.print(engineOilStats.maximum());
Serial3.print(" F");
Serial3.print("\t\t\t\tAVG: ");
Serial3.print(engineOilStats.average());
Serial3.println(" F");

SD Card Logging:
logfile.print(eOilTempF);
logfile.print(",");
logfile.print(checkEngine);
logfile.print(",");
logfile.print(engineOilStats.maximum());
logfile.print(",");
logfile.print(engineOilStats.average());
logfile.print(",");

tl;dr
My datalogging section of my sketch is 567 lines of mostly repeated code, and I'm new at programming and need some tutorials/terms to google to make it more effecient.

You can combine the Streaming library with a wrapper class that sends data to multiple serial destinations.
Here's a little example:
#include <Streaming.h>

class DualSerial : public Print {
    private:
        Print *_dev1;
        Print *_dev2;

    public:
        DualSerial(Print &s1, Print &s2) : _dev1(&s1), _dev2(&s2) {}

        size_t write(uint8_t c) {
            _dev1->write(c);
            _dev2->write(c);
        }
};

DualSerial remote(Serial, Serial3);

void setup() {
    Serial.begin(115200);
    Serial3.begin(115200);
}

void loop() {
    // Both Serial and Serial3 will receive this
    remote << "The time is: " << millis() << endl;
    delay(1000);
}

The Streaming class will work with anything that inherits from the Print class, which includes the SD card's File class, so you can also use it for writing to the SD card:
logfile << eOilTempF << ","
        << checkEngine << ","
        << engineOilStats.maximum() << ","
        << engineOilStats.average() << endl;


DC Motor not behaving reliably Using an Arduino Mega. I have a motor hooked up exactly like the picture below. Using a BC548B transistor, 1N4001 diode, 220 ohm resistor and a 9V battery. I'm driving the motor in code by using PWM analogWrite to value 255. Weird thing is, if hooked up to USB (5V), the motor will only start to move after a certain amount of time, seems like it needs some initial "drive" to get started. If using the 9V battery it starts up quicker, but still not directly, as I would expect. Also, if I set analogWrite to some value less than 255, it will not move at all - is the transistor limiting? Can I change the resistor value to compensate? Thanks for any advice.

int motorPin = 3;
int interval = 10;
int walkingTime = 7.5;
bool walking = false;

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

void loop() {
  delay(interval * 1000);
  if (!walking) {
    startWalk();
    delay(walkingTime * 1000);
    stopWalk();
  }
}

void startWalk() {
  walking = true;
  analogWrite(motorPin, 255);
}

void stopWalk() {
  walking = false;
  analogWrite(motorPin, 0);
}

Summary:

Your transistor is the wrong way round.
Rotate it 180 degree (so that collector and emitter are swapped) and it should work.

There are much better transistors available for this job, but this one should work when correctly connected.

Swap, test, report back.

The blue wire goes from emitter (right hand lead) to Arduino ground.

Longer:

The transistor is almost certainly "backwards" as above. More on that below, but first some comment on the actual transistor used and a superior alternative.

While it should work better than you describe, the BC548 is not a very good transistor for motor driving. It's maximum collector current is 100 mA. While you do not state the required motor current, within sensible limits a good guide is that the more a transistor can handle the better it will work, all else being equal. A 500 mA rated part would work better. An excellent pair of small transistor for "playing" are the BC327-40 (PNP) and the complementary BC337-40 (NPN). These have guaranteed current gains (effectively current amplification factor) of 250 and typically of 400. They are typically rated at 45V and 500 mA.
The Fairchild versions data sheet here from Digikey have an absolute maximum 800 mA rating. While the part was originally a European one it is widely available in the US and Asia and is usually about the same price as transistors with substantially inferior specs. eg see Digikey pricing below for BC548B and BC337-40 in 1, 10 and 100 quantity. The BC337 costs 1 cent more per transistor in each case. The BC337 comes in 3 versions with suffixes -16, -25 and -40. This relates to the current gain. The -40 part has an average Beta or current gain of 400. This is better (higher) than most alternatives and costs little or no more than the lower gain -16 and -25 parts.

BC548B datasheet here
BC337-40 datasheet here

BC548B pricing
1 10 100 prices are 22 / 20 / 11 cents each.

BC337-40 pricing
1 10 100 prices are   23 / 21 / 12 cents each.

According to that the pinout is CBE (collector base emitter) left to right looking at flat front with pins down. There are occasionally variations between manufacturers (but should not be) but if the datasheet matches your transistor it is "in backwards".

Swap C & E by rotating 180 degrees and report back.
With C&E swapped it acts like an NPN withj very low current gain.

Note: Presumable where you saay digitalWrite you meant analogWrite?


DS3231 RTC module and battery problem I've a CR2032 battery connected to DS3231 module as backup battery, when module is connected to 5V the battery voltage is at 4.3V and without power 3.7V.

That means the module is trying to charge the nonchargeable battery, i couldn't find a chargeable (LIR23032) battery to buy and after some research someone in forums suggested to remove the diode from the module...

If i keep using the CR2032 battery for long run 24/7, how long will battery last? is there a chance of explosion?
is there any other way than modifying the module it self?

If i keep using the CR2032 battery for long run 24/7, how long will battery last? is there a chance of explosion?

Yes. Recharging a non-rechargeable battery is dangerous. It should be avoided at all costs.

  is there any other way than modifying the module it self?

You have to prevent the power getting to the battery. That power is fed through a diode (hence 4.3V, which is 5V minus 0.7v for a silicon diode forward voltage).  Without knowing what the module is, I can't tell you if there is any other way that modifying it - however I would guess that no there isn't. You need to stop that power getting to the battery, and that can only be done at some point between where the power comes in to the module and the battery itself - and the simplest method is to remove the diode.

The purpose of that diode is to prevent power from the battery from trying to power the rest of your circuit when you remove the main power. Removing the diode will have no adverse affect.  You just won't be able to charge a rechargeable battery in future.


Square wave based on falling edge of alternative pulse of upcoming RPM square wave In my recent project, I have RPM Square wave from vehicle. Now, based on that I want square wave based on falling edge but only alternative pulse of RPM square wave.

I think below image clear more properly.

Upper yellowish square wave which I need. And below pinkish square wave is RPM square wave.

I made a code for that and it's working fine but when RPM is stable. But when RPM change rapidly then it's not working fine.

const int kPinRPM = 3;        // RPM / Digital Pin 3
const int RPMInterrupt = 1;   // RPM's interrrupt pin
byte engineCylinders = 2;         // Engine cylinders = 4;
byte engineCycles = 4;            // Engine cycle = 2
int refreshInterval = 750;        // Milliseconds between sensor updates
unsigned long previousMillis = 0;
volatile int RPMpulses = 0;
int RPM, Final_RPM;

const int kPinInj = 12;

volatile uint32_t kInjTime = 0;

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

  pinMode(kPinRPM, INPUT_PULLUP); // Enable internal pullup
  attachInterrupt(RPMInterrupt, countRPM, FALLING); //Interrupt for RPM

  pinMode(kPinInj, OUTPUT);
}

void loop()
{
  if(millis() - previousMillis > refreshInterval)
  {
    previousMillis = millis();
    RPM =  getRPM();
  }

  Serial.println(RPM);

  if((kInjTime > 0) && ((millis() - kInjTime) >= 10))
  {
    kInjTime = 0;
    digitalWrite(kPinInj, LOW);
  }
}

void countRPM()
{
  RPMpulses++;

  if(RPMpulses % 2 == 0)           // Skip alternative pulse
  {
    kInjTime = millis();
    digitalWrite(kPinInj, HIGH);
  }
}

int getRPM()
{
  Final_RPM = int(RPMpulses * (60000.0 / float(refreshInterval)) * engineCycles / engineCylinders / 2.0);
  RPMpulses = 0;
  Final_RPM = min(99999, Final_RPM);
}

After SUGGESTION, updating my codes. But it output waveform has some problem. In white circle, you can see that problem.

There are some things you shouldn't be doing within an interrupt service routine (ISR) like countRPM():

Don't call the millis() function. It depends on other interrupts which will be disabled during the execution of your ISR.
Don't call digitalWrite or any other functions
Don't use execution cycles hungry operators like % (modulo). To obtain modulo 2, just use a bit mask for the LSB.

What you should actually be doing within the ISR is just setting/resetting a flag or variable. Then, do all your stuff in the loop() function according the value of the flag or variable.


SIM900a Mini Modem, IMEI 0, help with TX RX pins I have Simcom SIM900a GSM (SIM900a Mini DEV Board v3.9.2) and I am interfacing it with Arduino UNO.
I have no idea how to connect SIM900a to Arduino UNO.
What I did now is:

I connect the following Pin from above image to:
5 to: GND (Digital GND near Pin 13)
6 to: 5V of Arduino
2 to: GND of Arduino near 5V
3 to: Digital Pin 0 of Arduino (RX)
4 to: Digital Pin 1 of Arduino (TX)
1 to: (No idea)
From Picture option 7, 8, 9 are not connected to anything.
Can you please guide me am I doing right?
I am getting hard time to find out what is TX and RX in my SIM900a module as it is not written there.
My SIM900a looks like this, this(Schematics given) and this.
When I upload the sketch:
File > Examples > GSM > TestModem:
to Arduino, I got this output from Serial Monitor:

Starting modem test...ERROR, no modem answer.
Checking IMEI...Modem's IMEI: 0
Reseting Modem... Modem is functioning properly: IMEI: 0

PS:
I saw this schematic here which is way different than what I am doing.
PSS:
Hints, am I supposed to provide external power supply of 5 V 2 A OR do I need some kind of converters (TTL to RS232 converter) ?

Finally I found solution to this problem:
My Pins connections were wrong, it should not be: 0 and 1 it should be 2 & 3:
2 - RX Arduino
3 - TX Arduino

also SoftwareSerial.h is not working with SIM900A
Pins:
All connections should be like this:
SIM900A - Arduino
=================
VCC     - VDC (+5V)
GND     - GND
5VR     - Connect to Arduino TX (Pin 3)
5VT     - Connect to Arduino RX (Pin 2)

As discussed here.
Very important:
Any program with header/library: #include <SoftwareSerial.h> is not working but #include <GSM.h> is working fine. As SoftwareSerial.h only work with GSM Shield and SIM900A isn't a shield.
Program/Sketch to Upload:
/*
SMS sender

created 25 Feb 2012
Originally written by Tom Igoe
But this is modified version
*/

// Include the GSM library
#include <GSM.h>

#define PINNUMBER ""

// initialize the library instance
GSM gsmAccess;
GSM_SMS sms;

void setup(){
// initialize serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial){
; // wait for serial port to connect. Needed for Leonardo only
}
Serial.println("SMS Messages Sender");
// connection state
boolean notConnected = true;

// Start SIM900A GSM

while (notConnected){
    Serial.println("Status 1: Please wait a while, If it taking lot of time, \nmeans you have wrong pin connections.");
    // If your SIM has PIN, pass it as a parameter of begin() in quotes
    if (gsmAccess.begin(PINNUMBER) == GSM_READY){
    Serial.println("Status 2: GSM is ready.");
    notConnected = false;
}else{
    Serial.println("Status 3: Not connected");
    delay(1000);
  }
}
    Serial.println("Status 4: GSM initialized. " );

    // calling function to send message
    sendMessage();
}

void loop(){
    // empty loop
}

// method to send message to specific number just once.
void sendMessage(){
    Serial.print("Message is sending...: ");
    // send the message
    sms.beginSMS("03XXXXXXX "); // Replace XXXXXXX with your mobile number.
    sms.print("This is just some message"); // Message content, replace with your's.
    sms.endSMS();
    Serial.println("COMPLETE!\n");
    Serial.println("Message Sent...!\n");
}

Bam, It is working, and it successfully can send message.
Things to remember:

As everywhere being said you need to supply external power supply to SIM900A   it requires 5 Volts and 2 Amphs.

Connect GND of SIM900A to Arduino GND.

Connect VCC+ (above photo connection 2) to 5V pin of Arduino.

One Problem:
When I upload sketch of:

Example > GSM > TestModem:

to Arduino, I got this output from Serial Monitor:

Starting modem test...ERROR, no modem answer.
Checking IMEI...Modem's IMEI: 0
Reseting Modem... Modem is functioning properly: IMEI: 0

I cannot get IMEI from SIM900A but I can send message.


Fast random booleans I am looking for a way of generating booleans rapidly. For booleans, one usually uses random(0,2); but in my case I need about 250 booleans and calling random every time is slow.
So I thought about using all bits of a random number on the whole range as such:
randomSeed(100); // A seed to always keep the same sequence
long rdm = random(MIN,MAX);  // Generate a number in range MIN,MAX of type long
long mask = 1;
for(int i=0; i<32; i++){
    if((rdm>>i)&mask){
        //do something
    } else {
        //do something else
    }
}

But with this I have three questions:

What are MIN and MAX so that the LONG random uses all bits, with value ranging from -2,147,483,648 to 2,147,483,647 (arduino long type). I tried several MIN and MAX, also simply random(); but without success.
Is it a valid approach? Do I expect each bit to be uniformly distributed? Should I use fewer bits, e.g. random(0, 2^16); for a "better" distribution?
Is there some seed known to be good or bad at this?

My project
I am working on a device made of Neopixel LED strips. It is for a visual neuroscience experiment where each "pixel" is either ON or OFF. I need the speed to be able to reach high refresh rate (60-100Hz), with normal statistical distribution to avoid bias in neuron response analysis. With this approach, I can reach the desired speed but I'm concerned about the statistics. So I need a better understanding of random()'s behaviour to do it right!

I didn't try myself, but in the documentation it shows the MAX value is  2,147,483,647, which is 2^31-1. The MIN value I expect is -2^31, thus -2,148.483.648. Wondering what you mean by 'without success'.
Yes this is a valid approach. A 'perfect' random generator should be able to generate all values with an equal distribution. Since the values are within [-2^31, 2^31-1] this means all values within a 32 bit value is used, which automatically means all bits are also evenly distributed. So you can pick individual bits (as long as you use the entire MIN/MAX range).
In principle all seeds are good, as long as they are random. In the documentation it is advised to take an unconnected analog pin value. If you don't have one unconnected, you can use e.g. the millis function.


Programfault when dereferencing a 64bit int on due I am running into a strange behaviour with my code. The following works without problems on an Arduino Nano but it seems to crash on a DUE

void putData64(byte* packet, int pos, uint64_t data)
{
    uint64_t* h= (uint64_t*) (packet+pos+2);
    *h= data;
}

the problematic line seems to be the second one (*h= data) as commenting it out lets the program run without problems.

Similar, the following lines cause a problem on a DUE but run fine on a Nano:

char* data;
// ... data is filled with something
uint64_t* t= (uint64_t*) (data+1);
uint64_t test= *t;

Is there something I am missing?

I concur with Majenko's comment: it's probably a memory alignment
problem. I don't know the specifics of the Due, but when you access
memory in chunks of 32 bit data words on a 32 bit CPU, it can
happen that the architecture requires the data words to be aligned to
32 bit (i.e. 4 byte) boundaries. This means that the address
of an uint32_t or uint64_t should be a multiple of 4. Maybe
even 8 for a uint64_t, you will have to check.

The only solution to this issue is to fill the packet byte by byte:

void putData64(byte* packet, int pos, uint64_t data)
{
    union {
        uint64_t integer;
        byte bytes[8];
    } h = { .integer = data };
    for (int i = 0; i < 8; i++) {
        packet[pos+2+i] = h.bytes[i];
    }
}

Note that the AVR (in the Nano) is an 8 bit architecture with no
alignment constraints whatsoever.


Can I connect a camera without a shield? I have an Arduino Uno and an ArduCAM-mini 2MP camera:

http://www.arducam.com/tag/arducam-mini/

Is it possible to connect this camera, or similar cameras, to the arduino without a shield?  The only tutorials I've found use a shield.

edit - here is what my cam looks like:

Judging by the photo (below) it is specifically designed to plug into the SPI ports on a Uno or similar (that is, pins 10 to 13). The other two wires are going to the ICSP header, presumably to pick up +5V and ground.

So yes, most certainly you can use it like that. With the pins done like that it even points horizontally.

  It wasn't clear to me that I should bend the camera pins as such (mine has 8 pins pointing downward).

You can buy pins with a 90° angle. If yours are not already soldered on, I would use the bent connector. If the pins are already soldered on, then the camera would lie flat, so just rotate the Arduino itself to point to where you want it to.

However you would need to do something with the +5V and Gnd pins, so that they can be rerouted to the correct place.

Looking at another photo on that site.

The pins would match most of the pins on a Uno, like this:

The only one that is wrong is AREF - you need +5V into that pin, not AREF, which is why they bent those two pins outwards (+5V and Gnd) and ran wires to the ICSP header.

If you mean all your pins are at right-angles already, then you really only need to fix the +5V one (you can probably bend it up). This is the pin-out for the ICSP header (view from above):

As you can see, you can pick up +5V from pin 2 (Vcc). Alternatively, run the +5 wire over to where +5 is marked on the Uno on the other side.

Another possible approach would be to not bend anything, but solder on a wire to the +5V pin and leave it plugged into AREF. AREF is just an input (analog reference voltage) and it won't hurt to have it left at +5V.


How do I add or subtract to a pre-determined value without having it default back to the original value? Typical apologies in advance, it's been quite some time since I've tinkered with Arduinos. Using an Arduino Micro Clone (Pro Micro), TF02 LiDAR, and a Adafruit 1.2" 7-segment display, I've been working on a rangefinder that is able to be adjusted up/down by increments of 1. I've hit a wall though. I am unable to adjust the distance value without it returning to the original value. Say the distance is at 6'2". When I push the "up" button, the value is 6'3" but then returns to 6'2". Same applies for the "down" button. Also, when the distance is at, for example, 1'0", and I press the down button, instead of going to 0'11", it displays 0'99". I'm at a wall in terms of what I can do to resolve this.  Any help is appreciated!
*
#include <Adafruit_GFX.h>
#include "Adafruit_LEDBackpack.h"
Adafruit_7segment matrix = Adafruit_7segment(); //d pin 2, c pin 3
#include <SoftwareSerial.h>// soft serial port
#include <Wire.h>

//button stuff
int Up_buttonState = 0;
int Dn_buttonState = 0;
int Up_lastButtonState = 0;
int Dn_lastButtonState = 0;
const int  UpPin = 7;
const int  DnPin = 8;

//LiDAR stuff
int dist;// LiDAR actually measured distance value
int strength;// LiDAR signal strength
int check;// check numerical value storage
int i;
int uart[9];// store data measured by LiDAR
const int HEADER=0x59;// data package frame header
long inches, INCH, feet, ftin;

SoftwareSerial mySerial(9,10); //rx tx,

void setup()
{
pinMode(UpPin, INPUT);
pinMode(DnPin, INPUT);
 Serial.begin(9600);

 mySerial.begin(115200);//set the Baud rate of LiDAR and Arduino serial port
  #ifndef __AVR_ATtiny85__

  #endif
  matrix.begin(0x70);
}
void loop()
{

 if (mySerial.available())//check whether the serial port has data input
 {
    if(mySerial.read()==HEADER)// determine data package frame header 0x59
    {

      uart[0]=HEADER;

      if(mySerial.read()==HEADER)//determine data package frame header 0x59
      {
       uart[1]=HEADER;

      for(i=2;i<9;i++)// store data to array
         {
          uart[i]=mySerial.read();
         }
           check=uart[0]+uart[1]+uart[2]+uart[3]+uart[4]+uart[5]+uart[6]+uart[7];
           if(uart[8]==(check&0xff))// check the received data as per protocols //if data received

             { //start equations
               dist=uart[2]+uart[3]*256;// calculate distance value

               //equations for converting mm to ft,in
               inches = (dist * .3937);
               INCH = inches% 12;
               feet = (dist / 2.54) / 12;
               ftin = feet*100 + INCH;

               Up_buttonState = digitalRead(UpPin); // add 1 to ftin
                if (Up_buttonState != Up_lastButtonState)
                {
                  if (Up_buttonState == HIGH)
                  {
                    ftin++;
                  }
                  delay(500);
                }
                Up_lastButtonState = Up_buttonState;

               Dn_buttonState = digitalRead(DnPin); // subtract 1 from ftin
                if (Dn_buttonState != Dn_lastButtonState)
                {
                  if (Dn_buttonState == HIGH)
                  {
                    ftin--;
                  }
                  delay(500);
                }
                Dn_lastButtonState = Dn_buttonState;

               Serial.print(ftin);
               matrix.print( ftin , DEC );
               matrix.writeDisplay();

             }
      }
    }
 }

}

You wrote:

ftin = feet*100 + INCH;

What is this monster? I am not very familiar with imperial units (and I
wonder why anyone would still want to use them), but I believe a foot is
not 100 inches.
Oh, I see. The monster is a kludge to manage the display in feet &
inches. But note that it is computed at every loop iteration as a
function of the measured distance. I doesn't make sense to apply a
correction to the monster as it is going to be recomputed on the next
iteration. That's why the value “returns” to what it is supposed to be.
As to why the down button changes “100” to “99”, I think it is quite
obvious: 100 minus one is 99. It is not a good idea to do arithmetics
with the monster.
If you want the correction to persist, you have to store it in a global
variable (or static local), and add that variable to the measured
distance at every loop iteration. For example:
// In global scope:
int correction = 0;

// In loop():
dist = ...;
inches = dist * 0.3937008 + correction;  // correction added here
ftin = (inches/12) * 100 + (inches%12);  // only used for display

if (Up_lastButtonState == LOW && Up_buttonState == HIGH) {
    correction++;
    delay(500);
}
if (Dn_lastButtonState == LOW && Dn_buttonState == HIGH) {
    correction--;
    delay(500);
}

Note that the monster is used for display only. No arithmetics are
performed on it, as that would not make any sense.


What would be the best way of dynamically 'change' instances regarding dynamic memory? Since I'm very used to object oriented programming, I would like to use this into my design.
My application will have 4 led strips and each led strip will have a 'pattern' running on it. For this I like to create a base class and for each pattern a derived class. So this means I have 4 instances to a pattern. However, the pattern can change dynamically (based on music MIDI input). Each pattern has between 10-16 parameters.
I know dynamic memory allocation is mostly not a good idea in an Arduino. I'm using a Mega which has 8 KB. I found several 'solutions' but neither one I'm sure about. The first is not the solution but the way I should do it when I have 'plenty' of SRAM available (and simplified):
class Pattern
{
   public:
      virtual void Process();
}

class PatternA: Pattern
{
   public:
      void Process();

      // In example I only use 2 out of 10-16 parameters
      uint8_t SetColor(uint8_t colorIndex);
      uint8_t SetSpeed(uint8_t speed);

   private:
      uint8_t _colorIndex;
      uint8_t _speed;
}

// In this example I only use 2 out of 24 patterns
class PatternB: Pattern
(like PatternA but with its own implementation)

class LedStrip
{
   public:
       void SetPattern(Pattern* pattern);

   private:
       Pattern* _pattern;
}

Other derived classes may have other (named) parameters.
When changing instances, I would get something like this:
LedStrip::SetPattern(Pattern* pattern)
{
    delete _pattern;
    _pattern = pattern;
}

pattern* pattern = new PatternA(...);
ledStrip1.SetPattern(pattern);

However, since the new pattern may use more memory then the deleted pattern, there will be a memory gap. So this is not suitable for the Arduino to be used I assume.
Solutions:
1. Create all possible patterns beforehand.
Assume I would implement 24 patterns, and create any possible combination, I would have 4 (led strips) * 24 (patterns) * 13.5 (average number of parameters) = 1,296 bytes. This seems a bit much as only 4 are 'active'.
class LedStrip
{
   public:
      enum EPattern {A, B}

      void SetPattern(EPattern pattern);

   private:
      PatternA* _patternA;
      PatternB* _patternB;

      Pattern* _pattern;
}

To change pattern:
void LedStrip::SetPattern(EPatternpattern)
{
case EPatternA: _pattern = _patternA; break;
case EPatternB: _pattern = _patternB; break;
}

ledStrip1.SetPattern(EPattern::A);

Of course I could also pass a pattern where the patterns are created globally but this is does not matter for this example. The idea is to create 4 (led strips) * 24 (patterns) instances beforehand and never use delete. This means out of the 4 * 24 patterns, only 4 are used, 1 per led strip.
Of course this causes a lot of unused memory.
2. New/Delete
I create the 4 correct derived instances and when one pattern (instance) change, I delete the instance and create the new. When I put no (instance) variables in the derived class, this could work, but I have some specific questions regarding this solution:
I make sure all the max. parameters are in the base class and I 'cast' 4 instances of the base class to a derived class. This seems a bit of 'tricky' solution.
class Pattern
{
   public:
      SetParameter(uint8_t parameter, uint8_t parameterValue);
      uint8_t parameter GetParameter(uint8_t parameter);

   private:
      uint8_t _parameters[16];
}

class PatternA: Pattern
... (does not have any variables)

To change pattern:
delete ledStrip1.pattern;
ledStrip1.pattern = new PatternA();

Question: can I assume the deleted memory of the old pattern will be replaced by the new pattern as the memory usage is equal?
The downside of this way is that each pattern will have the worst-case amount of parameters in each instance, but this is not a problem (I only have 4 led strips).

I don't know what you'll make of this, but:
If you can set aside a properly aligned and sufficiently large memory block you can use the placement form of the new operator.
Placement new is essentially new without the the part that behaves like (and typically is) malloc.  Or put differently, it lets you construct an object inside of already allocated memory.  By "already allocated" I don't mean already allocated on the heap; the memory can come from whereever you want.  This more or less lets you make your own custom allocator with predictable behaviour that you don't get from generic heap allocator like malloc.
So you can set aside memory however you want.  It can be an array of unsigned char in static storage duration (global, static local, static member).  And placement new can put an object into it, or importantly, into part of it.  Basically you're making your own arena for your allocator.
It's up to you to align the memory correctly.  There are compiler keywords that can help with that.  You can also resort to an older technique oversizing the block just large enough so that a properly aligned sub-block exists and can be found within it.  However, on an 8-bit microcontroller like the AVR, there are no alignment requirements to speak of.
When it comes to using delete, well, you don't.  You just call the destructor on the object directly.  There are ways you could try to clean that up also.
If I become awake enough to completely understand your specific usage, I may try to make an example.  But that is the basic technique I'd consider.

Regarding avoiding new/malloc: the case against them it is often slightly overstated.  For example, doing a set of malloc / new at the beginning, and only the beginning, of your program and not thereafter is normally fairly stable and predictable.  For example, you can read a configuration out of eeprom in setup() and use that information to allocate say three "dynamic" "arrays" with malloc, that you know they won't total more than some testable maximum.  Maybe a slightly more accurate warning for them is something like: you will get into trouble if you don't have a reasonable understanding of your maximum heap usage and if your usage pattern requires that you free/delete/remalloc.
I mention this in part also because it's not completely unreasonable to malloc/new once, early in your execution, to acquire an arena to use with placement new calls.


How can I discard power from a device I want to read from? I want to read the data line from a device that normally interfaces with a controller. It has 3 pins, 3.3v power, gnd, and data. I don't need the power line since the Arduino will be USB powered and I obviously don't want to just connect it straight to ground. What would be the best way to handle this without introducing extra hardware components. Can I just connect the power to an input pin, and then I can use that to see if the device is on?

I'm using an Arduino Mega2560

You don't need to "discard" power. You just ignore it.

If you don't need a connection, then don't connect it.  The only important connection is the ground connection. Everything else can be used, or not used, at your discretion.

There's nothing "magical" about a power connection. It's just a voltage that comes from a source that happens to be able to provide more current.  If you want to use it to power something, you can. If you want to just sense what the voltage is, you can. If you want to ignore it, you can.

It's not like a mountain: just because it's there, it doesn't mean you have to climb it...


Arduino Uno and ESP8266 serial monitor issue I plugged in the Arduino Uno and the ESP8266 following this schema:

When I enter "AT" in the serial monitor, I get an "OK". I can also connect to my wifi using typical ESP8266 commands.

What doesn't work is passing these commands using an Arduino Script. For example, if I use this script, I don't get an "OK" from the ESP8266.

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

 void loop() {
  // put your main code here, to run repeatedly:
 Serial.println("AT");
 delay(10000);
   if(Serial.find("OK")){
    Serial.println("OK");
     }
     else{
     Serial.println("NOT OK");
  }
}

I tried a bunch of different codes,and nothing works. What am I doing wrong?

What you are doing wrong is:

If sending AT commands from PC to ESP and receiving OK ,as you said, works - that means you connected TX output from USB --> RS232 IC on the board to both RX pin of the ATmega328 and RX pin of the ESP8266 - not as in your picture. Similarly, you connected RX input of the USB --> RS232 IC on the board to both ATmega328 TX and ESP8266 TX pin of the ESP8266. If communication between PC and ESP works, then you connected TX Arduino pin with TX ESP pin and RX Arduino pin with RX ESP pin and not as shown in the picture.

When you send AT command from PC both ATmega328 and ESP8266 are getting the signal from USB --> RS232 IC in their RX pins. As your firmware in the first 10 seconds doesn't read the RS232 data, ATmega328 just ignores the packets sent by PC but ESP8266 receives the packets and responds with OK.

Since you shorted RX on ATmega328 and RX on ESP8266 and you shorted TX on ATmega328 and RX on ESP8266, ATmega328 can not send the data to ESP and vice versa so there is no OK.

In the other case, if you connected ATmega328 TX with ESP8266 RX and ATmega328 RX with ESP8266 TX (as shown in the picture) then you would have shorted USB --> RS232 IC's TX with ESP's TX and you would have shorted USB --> RS232 IC's RX with ESP's RX.

In that case ATmega328 might be able to send AT command to both ESP and PC at the same time and ESP would respond but now ESP's TX would be connected to ATmega's RX which is now shorted with USB --> RS232 IC's TX so PC can't receive that packet. However, when ATmega328 responds with OK, the signal now goes from ATmega328 TX to USB --> RS232 IC's RX (as always) and you might see the response in serial terminal.

So, you can't get the ESP to respond directly to PC and to ATmega328 without interchanging the TX/RX wires. Furthermore, as you may know RS232 is designed for communication between two devices, not three - and this is the case where three devices (USB --> RS232 IC, ATmega328 and ESP8266) are connected to the same TX/RX pins at the same time in a rather unusual way. Because, devices are usually connected TX to RX and RX to TX. However, when using the Arduino's onboard USB --> RS232 converter (by removing the microcontroller or holding it under reset) then you have to connect TX to TX and RX to RX. That is because there is one more TX/RX pair in between PC and the RX/TX pins on the board. The output of the USB --> RS232 converter (TX) sends the data to RX pin on ATmega328 (and RX pin on the board) but if you want to send the signal further (to some other device), then the pin marked with RX is going to act as TX.

To summarize:

The schematics does not correspond to what you have written. Such a connection would not allow to send the AT commands from the PC to ESP and to receive response, meaning you connected the TX/RX the other way round.
You can not have both at the same time. You have to decide whether you want to send AT commands from the PC or from microcontroller and then connect the wires accordingly.