<issue_start>username_0: I am stumped. I have a few Wemos D1 Mini boards that were working on the local WiFi yesterday, yet today none of them will connect. More puzzling is that I can flash Tasmota on them and they all connect to the WiFi, but none with this code that was working yesterday. Any tips would be appreciated.

```cpp
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);

  //Connect to WiFi network so we can reach the MQTT broker and publish messages to topics.
  WiFi.mode(WIFI_STA);
  WiFi.begin(wifi_ssid, wifi_password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.print(F("WiFi connected, "));
  Serial.print(F("IP address: "));
  Serial.println(WiFi.localIP());
}

```<issue_comment>username_1: Solved. (sort of). This is a working workaround.

I have determined that if I use ESP8266WiFi library Version 2.5.0 or later, all I get from WiFi.status() is WL\_NO\_SSID\_AVAIL.

By reverting to ESP8266WiFi library Version 2.4.2, I can get a connection with the same sketch.

(Juraj's comments pushed me in the direction of trying older library versions.)
Upvotes: 0 <issue_comment>username_2: Assuming that it's not something silly and accidental like the password or ssid being changed in your code, there are two things you may be running in to:

1. The WiFi.begin() function is technically not needed more than once. Values written with it are stored in a separate part of flash memory that is not overwritten by any sketch uploads. Since it's stored persistently, it may start connecting before your connection code is called. This causes a race condition that triggers a bug in the library that is, to my knowledge, still present, and can break the WiFi subsystem. If this has happened, the reason that the other firmware might work is if it fixes the error or somehow uses a different method.
You can work around this by waiting a few seconds and then trying to connect if it's not currently connected.
Try this fix: <https://github.com/kentaylor/EraseEsp8266Flash> to see if that's the problem. Alternatively, you can try some of the options in the first link of my next item to see if those work for this purpose.
2. Remember how I said that the functions persist data in flash? That has a limited write count, and no, that partition has no wear-leveling. After so many writes (and, since begin() is called in setup, it does so every time the device starts or wakes!) it will fail to hold the correct values. The endurance can be quite poor on some cheaper flash devices (and cheaper boards). But, if you want to keep using begin() to set up the WiFi (rather than set it once the normal way and then make sure begin() isn't called again by your code), delete the stored parameters ([Does the ESP8266 somehow remember wifi access data?](https://arduino.stackexchange.com/questions/52059/does-the-esp8266-somehow-remember-wifi-access-data)) and then turn off persistence ([esp8266 advertising AP even when flashed with custom firmware](https://arduino.stackexchange.com/questions/63187/esp8266-advertising-ap-even-when-flashed-with-custom-firmware)). I also suggest running the following code fragment to turn off persistence and then **stop** turning it off (since THAT change persists too!):

if (WiFi.getPersistent()) {
 WiFi.persistent(false);
}

This latter case is known to break Arduino projects, but NOT nodeMCU Lua ones. If the Tazmota firmware uses a different method, it could also ignore this issue but your code might experience it. To test this, try running the code on a different board (can be the same type, just so long as it's not the same one).
Upvotes: 0 <issue_comment>username_1: Fixed.
My router is ancient and does not support WPA. As of ESP8266WiFi library Version 2.5.0, WPA is is the preferred mode. The solution is to get a better router, or add WiFi.enableInsecureWEP(); before calling WiFi.begin().

```
WiFi.enableInsecureWEP();
WiFi.begin(wifi_ssid, wifi_password);

```
Upvotes: 2 [selected_answer]


<issue_start>username_0: I am new to using an Arduino and I am trying to program my it to implement a ﬂashing pattern with two LEDs. When one LED is oﬀ, the other must be on. The program needs to be done in assembly. I have a working program in c++ but I need to convert it to assembly. I have an Arduino UNO ATmega 328p

Here is my c++ program:

```
 const int led = 13;
 const int led2 = 12;

 void setup() {
    pinMode(led, OUTPUT);
    pinMode(led2, OUTPUT);
 }

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

```<issue_comment>username_1: Try this method to convert your sketch

<https://sourceforge.net/projects/arduino-to-assembly-converter/>
Upvotes: 0 <issue_comment>username_2: In the case, that this is a school assignment and you actually have to program directly in assembler, you probably don't want to directly convert your C++ sketch. It will generate way more assembler code, than is really necessary for alternatively blinking two LEDs (for example `digitalWrite()` contains not only the actual writing to the corresponding pin registers, but much more code), and it will be obvious, that you didn't write it yourself.

In this case you have to go the harder way. You should start by looking into existing assembler blink programs. Via google I found [this series](https://gist.github.com/mhitza/8a4608f4dfdec20d3879) at github gist, which also has a blink example. You can derive some of the program from there. Also there is a list of assembler command with descriptions.

In the end everything, that is done on a microcontroller, comes down to reading and writing Special Function Registers (SFR). The pins are organized in ports with 8 (or sometimes less) pins. Every port is then represented by one byte in the corresponding SFR (1 bit per pin). For changing the direction of a pin between output and input, the DDRX registers are used (where X is the character of the port used). For actually setting the output state (or enabling/disabling the internal pullup resistor) the PORTX registers are used. The current state (LOW or HIGH; while input or output) can be read from the PINX registers. For these things, the datasheet of the microcontroller (here the Atmega328P) is a must read (meaning: not completely, but enough to feel comfortable getting needed information from it).

Learn how to set single bits in a byte (in a SFR). You can learn it from the linked example, or from tutorials over the internet. Then write code to write the correct value to the corresponding DDRX bits to set the LED pins to output. Then you can use this to write a value to an output pin.

For blinking you need a timer. If you google for something like "arduino assembler blink" you will also find an example, which configures the timer for blinking. Basically it involves setting the Timers SFRs to the wanted values. If you don't want to do this, you might get away with executing a high number of "nop" operations (which does nothing). You would have to write a loop, that will execute a high number of times. ( very "nop" will need 1 clock cycle - credits to Ghanima for searching that up). The clock runs on 16MHz, so you can do the math to calculate, how long 1 "nop" needs, and then calculate, how many of them you need).
Upvotes: 2 <issue_comment>username_3: It "needs" to be done in assembly as an assignment, right? Otherwise you would "want to learn" assembly.

What I suggest you do is change the C program to use port manipulation, for example:

```cpp
 void setup() {
   DDRB |= 0b00100000;  // D13 to output mode
 }

 void loop() {
   PORTB |= 0b00100000;  // turn on D13
   delay(2000);
   PORTB &= ~0b00100000;  // turn off D13
   delay(2000);
 }

```

Now at least you are flashing D13 without using the rather complex digitalWrite and pinMode library functions. The delay is another issue I'll leave you to investigate however [my page about timers](http://www.gammon.com.au/timers) might help you.

Now you can disassemble the generated code to see what the compiler generated in assembler and use that to help you learn how to do it.

For example, when I compiled the above code and turned on "verbose compiling" I found the location of the generated .elf file.

Running avr-objdump on that file (like this):

```
avr-objdump -S /tmp/build436d41bc5c0da39afe99cd9c05ac272a.tmp/sketch_aug13a.ino.elf > temp.txt

```

Gives me the following code for "loop":

```none
00000094 :
 94: 2d 9a sbi 0x05, 5 ; 5
 96: 60 ed ldi r22, 0xD0 ; 208
 98: 77 e0 ldi r23, 0x07 ; 7
 9a: 80 e0 ldi r24, 0x00 ; 0
 9c: 90 e0 ldi r25, 0x00 ; 0
 9e: 0e 94 c5 00 call 0x18a ; 0x18a
 a2: 2d 98 cbi 0x05, 5 ; 5
 a4: 60 ed ldi r22, 0xD0 ; 208
 a6: 77 e0 ldi r23, 0x07 ; 7
 a8: 80 e0 ldi r24, 0x00 ; 0
 aa: 90 e0 ldi r25, 0x00 ; 0
 ac: 0c 94 c5 00 jmp 0x18a ; 0x18a

```

What we basically see there is one "sbi" instruction to turn the LED on and one "cbi" instruction to turn it off.

As for the rest, well I don't want to do your homework for you. Have fun learning how to program in assembler!
Upvotes: 1 <issue_comment>username_4: There are also a couple of ways of including assembler code right inside your Arduino IDE.

By including the assembler in the Arduino IDE, the assembler source is assembled and linked into your project and uploaded to your Arduino from within the IDE - just like any other program.

This makes it easy to get started with Assembler while still retaining the familiarity of the Arduino IDE. Why? Because since you can mix C / C++ code with the Assembler code this means that you do not have to write a complete assembler program that manages all of the hardware initialisation nitty gritty - you can start small and expand your assembler as and when you you feel comfortable or need to do so. Like the example below, you can start with just two lines of assembler that fit into a larger program if you wanted to.

Following are the instructions for creating a mixed C / Assembler program in Arduino. I also give an example of how to pass parameters and get a result from an Assembler function.

To create a mixed C + Assembler program create a new project in the Arduino IDE (call it whatever you like) and enter the following code into the IDE:

```
extern "C" {
  void myInit();
  void myLoop();
  int myAdd(int, int);
}

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

  // This is just a dummy example showing inline assembler using the asm "directive"
  // Refer to this tutorial, or similar, for details of inline assembler in Arduino:
  // https://ucexperiment.wordpress.com/2016/03/11/arduino-inline-assembly-tutorial-5-2/
  asm(
    "ldi   r26,42"
  );
}

void loop() {
  myLoop();

  int ans = myAdd(240, 25);
  delay(ans);
  Serial.print("Answer: ");
  Serial.println(ans);
  delay(1000);
}

```

Next click the little down arrow in the top right corner of the IDE as per the following diagram and select "New Tab":

[![Arduino IDE - Add New Tab](https://i.stack.imgur.com/BSEtN.png)](https://i.stack.imgur.com/BSEtN.png)

Enter `myFunctions.S` as the name of the new tab as shown below. Note that the name does not really matter, but, it **must end with the extension .S** and the "S" must be a capital "S" not a lowercase "s":

[![Arduino IDE - Name the New Tab](https://i.stack.imgur.com/uEL0b.png)](https://i.stack.imgur.com/uEL0b.png)

Paste the following code into the `myFunctions.S` tab.

```
; Example assembler file that blinks an LED.
; and adds two numbers together.

#define __SFR_OFFSET 0

#include "avr/io.h"

// Declare the three function entry points as "globals"
.global myInit
.global myLoop
.global myAdd

myInit:
  sbi   DDRB,5      ; Set PB5 (the built in LED on Arduino Uno) as output
  ret

myLoop:
  ldi   r20,250     ; Set the delay duration in ms. Maximum value is 255.
  call  myDelay_ms
  sbi   PORTB,5     ; Set PB5 HIGH
  ldi   r20,250     ; Delay for another 250 ms.
  call  myDelay_ms
  cbi   PORTB,5     ; Set PB5 LOW
  ret

; These symbols are for internal to this assembler file's use only.
; They are private because they are not listed as a global symbol
; Also, they do not conform to the subroutine calling conventions used
; by the Arduino IDE's compiler. i.e. they are not compatible with
; being called directly from C. However, since we are calling them from
; our own assembler, we can (almost) make up any calling convention we like.
myDelay_ms:
  ; Delay about r20*1ms. Destroys r20, r30, and r31.
  ; One millisecond is about 16000 cycles at 16MHz.
  ; The basic loop takes about 5 cycles, so we need about 16,000,000 / 5 = 3000 loops.
  ; NB: most instructions are 8 bit, so we load the 16 bit counter using
  ;     two 8 bit loads.
  ldi   r31, 3000>>8    ; high(3000)
  ldi   r30, 3000&255   ; low(3000)
delaylp:
  sbiw    r30, 1        ; Decrement our 1 ms counter (this instruction operates on a 16 bit value in R31:R30).
  brne    delaylp       ; If R30 is non zero, loop back
  subi    r20, 1        ; Otherwise we have passed 1 ms so, decrement the high order byte of our counter.
  brne    myDelay_ms    ; If this is non zero, loop back.
  ret                   ; Otherwise, we have counted down from R20 * 3,000 - so return.

; Function to add two integers and return an integer.
; For few parameter functions, the Arduino IDE uses registers built into the
; Microcontroller (i.e. the CPU) to exchange data between subroutine caller and callee.
; Return values are as follows:
;   - single Byte (e.g. char, byte) R24 only
;   - double Byte (e.g. int)        R25:R24 (R25 is the high order byte)
;   - quad Byte   (e.g. long)       R25:R24:R23:R22 (R25 is the high order byte)
; Parameters are passed in similar ways starting with R25 and working down, but exactly
; what is where will depend upon the parameter types.
; Refer to this tutorial for more details or the AVR compiler documentation from ATMEL
;   https://ucexperiment.wordpress.com/2016/04/02/arduino-inline-assembly-tutorial-12-functions/
; In our case, a is passed in R25:R24 and b is passed in R23:R22
myAdd:
  add     r24, r22      ; Add the low order bytes
  adc     r25, r23      ; Add the high order bytes PLUS any value carried from the previous addition.
  ret                   ; The result is in R25:R24 which is where it needs to be to pass back to the C code.

```

Upload it to your Uno, start the serial monitor and you should see some sum's being ouput (well one sum continuously being output). Feel free to change the values in the main loop to see different results.

I've put loads of comments and a few references into the code to get you started on the path to finding more information.

One other reference that will be useful if you are going to mess with assembler on the UNO is the ATMega-328P reference manual/datasheet (all 662 pages of it) which you can obtain from [Microchip's ATmega328p reference page](https://www.microchip.com/wwwproducts/en/ATmega328p). There are a whole bunch more useful resources there that will likely come in handy from time to time.
Upvotes: 2


<issue_start>username_0: I am designing a circuit connected to a simple open-close sensor, like a switch. For ease of construction, the circuit with the sensor switch closes to ground, and uses a 1 MΩ pullup resistor to Vcc to signal `HIGH` when the switch is open.

I realize that power is flowing the entire time the switch is open, which may (or may not) drain the battery. Would it be more efficient to use a pulldown resistor to ground, and have the switch open to Vcc?

Tangentially, should there be a resistor on the connection to Vcc as well? Either to reduce current (save battery power) or prevent damage to the ATmega328?

Thank you!<issue_comment>username_1: Sure, no reason that wouldn't work. For best results you want a known resistor of about the same resistance as, or a little below, the one you are measuring.

However, if what you are seeing is an actual open circuit then there's little benefit to measuring the resistance - you may as well just treat it as a switch or button, give it a large pullup, and use a digital input (or even an interrupt) to give a simple "OK / ERROR" signal.
Upvotes: 1 <issue_comment>username_2: For data communications the problem is often more complicated than DC resistance. Data signals are AC, and subject to impedance, (not simple resistance) inductance, and capacitance, as well as RF interference. A pair that's fine for slow on/off switching of DC signals may not be fine for higher frequency data signals.

You can also get intermittent shorts between wires in one pair and other pairs, even if the connection between the wires in the test pair are fine.

Back in the day I worked for a company that sold and serviced mini-computers to the US House of Representatives. The house offices would run serial cables up through walls and ceilings, and also under carpets. We had some flaky cables, and finally figured out that the offices would run the cables under the carpet, but over carpet tack strips. As people walked over the carpet, it would sometimes cause the tack strips to poke through the insulation, causing shorts and RF noise in the cables, which would mysteriously go away later.

Checking DC resistance will let you find breaks in your wires, but you can't assume that if the DC resistance looks good, the pair is good.

I would suggest using a simple voltage divider and one of the input lines on the Arduino for simple resistance testing, but that will only get you so far.

What you really want is a signal generator and an oscilloscope. You should send test signals (With voltages and signal patterns that resemble your data signals) down one pair at a time, and look at the signals on the far end, checking all the pairs. You should see your test signal come through, with the wave pattern still recognizable on the target pair, and no significant leaking of the signal to other pairs.
Upvotes: 0


<issue_start>username_0: I have an Arduino and a [microswitch](https://uk.rs-online.com/web/p/microswitches/1594590/) that I want to use to know when the switch is initially being pressed (get "OnsetTime" on Serial) and when the switch is not being pressed anymore (get "OffsetTime" on Serial).

Imagine a bird sitting on the switch. I want to get an output "OnsetTime" when the bird first sits on the switch and an output "OffsetTime" when the bird flies away from the switch.

Right now, I have an output that constantly prints out "OnsetTime" when the switch is pressed.
I would appreciate it if anybody can help me figure out how can I implement the below code to get the outputs only when the switch is initially pressed and not being pressed anymore.

```
void setup() {
  pinMode(7, INPUT);
  Serial.begin(9600);
}

void loop() {
  if (digitalRead(7) == HIGH) {
    Serial.println("OnsetTime");
    }
}
    //Serial.println("GetOffsetTime");

```<issue_comment>username_1: You have two possibilities of powering the shield according to the adafruit documentation.

A: power the Arduino over the power plug (not the USB plug) of the Arduino and set the VIN jumper.

B: Leave the VIN jumper off and power over the power connector of the shield.

Don't try other possibilities. They may kill the shield or the Arduino.

The reason your motor doesn't turn is because you switched it off
`myMotor->run(RELEASE);` immediately after you switched it on `myMotor->run(FORWARD);`.
Upvotes: 2 [selected_answer]<issue_comment>username_2: I just used a different motor-shield and it works now, thank you all for your replies and research in this!
Upvotes: 2


<issue_start>username_0: I think many people know about the staircase lights, which will get triggered by 2 PIR-sensors (1x upstairs and 1x downstairs).

Here is my code - which works well. It's not cleaned up - as i don't know how i can simplify it. I think there'll be a much nicer way of getting the same output. :)

```
#include "FastLED.h"
#define NUM_LEDS 300
CRGB leds[NUM_LEDS];
#define PIN 3
int sensorUP = 5;
int sensorDOWN = 7;
int state = LOW;
int valUP = 0;
int valDOWN = 0;

void setup()
{
  FastLED.addLeds(leds, NUM\_LEDS).setCorrection( TypicalLEDStrip );
 FastLED.setBrightness(20);
 pinMode(2, INPUT\_PULLUP); // internal pull-up resistor
 pinMode(sensorUP, INPUT);
 pinMode(sensorDOWN, INPUT);
 Serial.begin(9600);
}

void loop() {
 valUP = digitalRead(sensorUP);
 valDOWN = digitalRead(sensorDOWN);

 if (valUP == HIGH) {
 colorWipeUP(0x55, 0xFF, 0x00, 2);
 delay(600);
 colorWipeUP(0x00, 0x00, 0x00, 2);
 delay(100);
 }
 if (valDOWN == HIGH) {
 colorWipeDOWN(0x55, 0xFF, 0x00, 2);
 delay(6000);
 colorWipeDOWN(0x00, 0x00, 0x00, 2);
 delay(100);
 }
}

void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
 for (uint16\_t i = 0; i < NUM\_LEDS; i++) {
 setPixel(i, red, green, blue);
 FastLED.show();
 delay(SpeedDelay);
 }
}
void colorWipeDOWN(byte red, byte green, byte blue, int SpeedDelay) {
 for (uint16\_t i = 299; i < NUM\_LEDS; i--) {
 setPixel(i, red, green, blue);
 FastLED.show();
 delay(SpeedDelay);
 }
}

void setPixel(int Pixel, byte red, byte green, byte blue) {
 leds[Pixel].r = red;
 leds[Pixel].g = green;
 leds[Pixel].b = blue;
}

void setAll(byte red, byte green, byte blue) {
 for (int i = 0; i < NUM\_LEDS; i++ ) {
 setPixel(i, red, green, blue);
 }
 FastLED.show();
}

```

At the moment the LEDs just go on and after a delay off again (one-by-one).

QUESTION: I wish for a little smoother effect by fading them on and off.
So i reached the actual output by using different snippets and trying to understand. What i don't understand atm is how to add fading.<issue_comment>username_1: Your code is currently written as blocking, so we can leave it that way and add another blocking nested loop. Let's take the `colorWipeUP()` function as example:

```
void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  for (uint16_t i = 0; i < NUM_LEDS; i++) {
    setPixel(i, red, green, blue);
   FastLED.show();
    delay(SpeedDelay);
  }
}

```

You go through all leds, lighting them up one after another with the provided color, delaying between the LEDs. The brightness of an LED is controlled by the overall RGB value. If you just multiply the RGB components red, green and blue with a number between 0 and 1, you (mostly) keep the color and only control the brightness. For example like this:

```
void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  for (uint16_t i = 0; i < NUM_LEDS; i++) {
    for(uint8_t brightness = 0; brightness <= 100; brightness++){
      setPixel(i, red*brightness/100, green*brightness/100, blue*brightness/100);
      FastLED.show();
      delay(fadeDelay);
    }
    delay(SpeedDelay);
  }
}

```

For every LED we are now going from zero brightness to 100% brightness in a loop, showing each individual step on the LED strip. `fadeDelay` determines, how fast this fade in should be. You will have to tune both delays to fit your expectations. You can use the same principle for the wipe down.

You may be asking yourself, why I count from 0 to 100 and then dividing by 100 instead of directly counting from 0 to 1 in steps of 0.01. I've done this, because on AVR based microcontrollers you don't have native floating point calculations. This means, that every floating point calculation needs many instructions to execute (because the floating point math is implemented in software instead of hardware). Here I'm counting with integers and when calculating the brightness also only integer math is involved (dividing by 100 is an integer division, which will automatically cut all digits after the decimal point. We don't need them).

Note: With 300 LEDs, the call to `FastLED.show()` will take some time. I haven't tested the code, but depending on your needs the fading might be too slow, even when you remove the delay call. Then you can simply increase the increment of the for loop, for example to use 10 steps instead of 100:

```
for(uint8_t brightness=0; brightness<100; brightness+=10)

```

---

>
> something like a fade over 10 LEDs
>
>
>

For this I would use a totally different approach. If you view it mathematically, the brightness of each LED is a function of position and time. So we can implement a function much like a mathematical function, that returns the brightness for a given position and a given time. As I understood, you want the a function, that is first constantly zero, then it grows linearly with time and position and then it is constantly full brighntess. We can count the time from the moment, that the sensor is triggered, where we then start with zero brightness and let it rise linearly. Something like this:

```
int fadeBrightness(int position, unsigned long time){
    int brightness = m_p*position+m_t*time;
    if(brightness > 100) return 100;
    if(brightness < 0) return 0;
    return brightness;
}

```

`m_p` and `m_t` are constants, that you would need to define and fine tune. For fading over 10 LEDs, `m_p` has to be `-10`. `time` is provided as milliseconds. I'm currently not sure about the value of `m_t`, but you can simply try some values and use one that's fitting.

Then in your `colorWipeUP()` function you can loop through all LEDs and set their pixel just like in the code above, but this time you use the newly created function.

```
void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  unsigned long timestamp = millis();
  while(millis()-timestamp < duration){
    for (uint16_t i = 0; i < NUM_LEDS; i++) {
      setPixel(i, red*fadeBrightness(i, millis()-timestamp)/100, green*fadeBrightness(i, millis()-timestamp)/100, blue*fadeBrightness(i, millis()-timestamp)/100);
    }
    FastLED.show();
  }
}

```

You need to define the `duration` according to how long the fading will take with your `m_t`. If you set it longer, the loop will just loop longer, holding the brightness at 100%.

In the function we first create a timestamp from the `millis()` function. Then we loop, while the duration of the effect hasn't passed. In each while loop iteration, we set the color components of each LED pixel with the brightness according to our `fadeBrightness()` function. Then we show this on the LED strip. The function is constantly updating the strip at max speed. The actual speed of the animation is determined by the `fadeBrightness()` function.

This version is also blocking code, but it can easily be transformed to non-blocking code, that you would call repeatedly until the animation is done.
Upvotes: 3 [selected_answer]<issue_comment>username_2: You could do something like this. (not tested)

```
void colorWipeUP(byte red, byte green, byte blue, int SpeedDelay) {
  for (int i = -5; i < NUM_LEDS + 5; i++) {
    setPixel(i    ,      red, green, blue);   // example only
    setPixel(i + 1, .8 * red, green, blue);   // change the green and blue also
    setPixel(i + 2, .6 * red, green, blue);
    setPixel(i + 3, .4 * red, green, blue);   // successive pixels have lower brightness
    setPixel(i + 4, .2 * red, green, blue);
    FastLED.show();
    delay(SpeedDelay);
  }
}

void setPixel(int Pixel, byte red, byte green, byte blue) {

  if (Pixel < 0 || Pixel >= NUM_LEDS) return;        // do not set color of non-existent pixels

  leds[Pixel].r = red;
  leds[Pixel].g = green;
  leds[Pixel].b = blue;
}

```
Upvotes: 0


<issue_start>username_0: i'm making a digital clock.
Right now the plan is to matrix them on a atmega328 using transistors.
I figured i need a transistor on both sides or the current would be sinked/sourced by the atmega, which is not what i want.

I'd rather use the MAX7219 but i'm not sure if it's possible to use transistors, because i don't think the MAX7219 can handle the current.

I found the circuits [here](https://forum.arduino.cc/index.php?topic=671697.0), i smushed them together, is this correct? Idk.

[![enter image description here](https://i.stack.imgur.com/soguz.png)](https://i.stack.imgur.com/soguz.png)

This is the led segment i'm using, there's four of them. So four 337 transistors, one for each digit. And seven 327 transistors, one for each segment.
I will scan through the four digits and turn on the apropriate segment.
[![enter image description here](https://i.stack.imgur.com/azIpc.png)](https://i.stack.imgur.com/azIpc.png)

So yea, please let me know if this is totally wacky or something else.

Edit :
I guess this would be 1 digit. Sorry it's confusing to draw the whole matrix. I hope this clears it up. It's just a normal matrixing situation but with more leds.
[![enter image description here](https://i.stack.imgur.com/r84zC.png)](https://i.stack.imgur.com/r84zC.png)

So normally it goes something like this :
**The cathodes of the leds are controlled directly by the atmega, but results in the atmega supplying the current. So my reasoning would be to put a row of transistors there instead, would that be correct?**
[![enter image description here](https://i.stack.imgur.com/qBJb0.png)](https://i.stack.imgur.com/qBJb0.png)<issue_comment>username_1: You define i,y,i as global variables so there is no need to hand them over to different functions. They can be accessed and changed in all parts of your program.

define instead of

```
int y;

```

change to

```
long y;

```

and change

```
 void inOut(int &i){

```

to

```
void inOut(){

```

and remove

```
   return i;// Its a global var

```

change the line

```
unsigned long y = ((sensorValue*i)/600);

```

to

```
y = ((sensorValue*i)/600);

```

Try to avoid the same names for global and local vars. It might happen that the compiler handles it as a redefinition, which might lead to all sort of trouble in complex programs. (Also for you if you look onto an ill documented code some months later)
And get rid of the delay it stops processing (also your subroutines) see Blinkwithoutdelay how to do it properly
ArduinoIDE->file->examples->2 Digital->Blinkwithoutdelay
Upvotes: 2 <issue_comment>username_2: Thanks for the help, this is my working code. I changed things to long, got rid of some long's, stopped passing variables, and forced number in sensorValue to be long. It now counts up and down were I set the potentiometer every minute.

```

int analogInPin = A0;
int analogOutPin3 = 3;

long sensorValue;

int i = 0;
int a;
long y;

void sens(){
  sensorValue = ((analogRead(analogInPin)*255L)/1023); //force 255 to be long
}

void inOut(){
  if (i > -1){
    i = i + a;
  if (i == 0){
     a = 1;
  }
  if (i == 600){
    a = -1;
  }
 }
}

void updateFade(){
  sens();
  inOut();
  y = ((sensorValue*i)/600);
  Serial.println(y);
}

void setup() {
  Serial.begin(9600);
  pinMode(analogInPin,INPUT);
  pinMode(3,OUTPUT);
}

void loop() {
  updateFade();
  delay(100);
  analogWrite(3, y);
}

```
Upvotes: 1


<issue_start>username_0: I am completely new to programming with Arduino so please bear with me if this seems stupid.

I am using an Arduino Uno R3.
I have two sensors, a Soil Moisture sensor and an LDR Light Sensor. Both of them have one pin marked as A0 on them. So now, do I connect them both to A0 using a breadboard (Like how I am connecting multiple sensors' VCC to the 5V pin currently) OR do I use a different analog pin say A0 for one and A1 for the other? Will it make a difference?<issue_comment>username_1: Here is a simple trick how to switch from integer math to floating point math and use round function.

```cpp
  unsigned long milliseconds = 599999;

  unsigned long minutes_long = (milliseconds/1000)/60;
  // minutes_long = 9

  double minutes_double = (milliseconds/1000.0)/60.0;
  // minutes_double = 9.99998...

  double minutes_rounded = round(minutes_double);
  // minutes_rounded = 10

```

There also exists a trick that allows calculation of `round` using integer math. It's perfect if you don't have enough memory for a cast.

```cpp
  unsigned long milliseconds;

  milliseconds = 600000 - 30*1000 - 1;
  //milliseconds = 569999

  unsigned long minutes_9 = (milliseconds+30000)/60000;
  // minutes_9 = 9

  milliseconds = 600000 - 30*1000;
  //milliseconds = 570000

  unsigned long minutes_10 = (milliseconds+30000)/60000;
  // minutes_10 = 10

```
Upvotes: -1 <issue_comment>username_2: To round to the nearest X in fixed point arithmetic: add 1/2 X (in the base units, msec, in this case) and divide by X (again, in the base units) so:
`milliseconds = (milliseconds + (30*1000L))/(60*1000L);`

The addition of 1/2 X causes a carry of one whole X if the fractional X in the original quantity was 1/2 X or greater. (Likewise, if the fractional X was less than 1/2 X, no carry will result).

Integer division naturally truncates any fractional amounts, so you'll be left with the rounded integer result.
Upvotes: 2


<issue_start>username_0: I want to compile a sketch on Arduino Uno, while Arduino is running and not connected to anything else, and then run the compiled sketch automatically.

Is this feasible?

How?<issue_comment>username_1: No. It's not feasible.

The Uno cannot compile. The Uno cannot run code from RAM. The Uno is *not* a computer.

You *might* be able to find some small scripting language that could run on an Uno, but TBH the Uno is so underpowered you'd be able to do little more than blink an LED...
Upvotes: 0 <issue_comment>username_2: No, not feasable, not possible.

The Arduino runs machine code and it does not have enough space or computation power for a compiler (also there is simply no version of the avr C++ compiler for the AVR platform, for obvious reasons). Also it is internally hardwired to run code from the flash memory. You cannot execute code from RAM. The Arduino is a microcontroller, not a computer. (Here I mean computer as something like: Has a microprocessor to execute code from RAM; has an OS; has huge amount of resources in relation to the average microcontroller)

Also: "not connected to anything else" --> Then how would you interact with the Arduino, writing the code, triggering compilation?

If this is about the cable connection, you can implement programming over bluetooth through the HC-05 module (google for it, there should be plenty of tutorials out there). Or go away from the Arduino and change to an ESP, so that you can do Over The Air (OTA) updates over wifi.

Or you could change to a minicomputer like the Raspberry Pi Zero, which is just a little bigger than the Arduino Nano and smaller than the Uno. (Though that hardly depends on the goal, what you are trying to achieve. Microcontrollers are sometimes better used for specific tasks in contrast to minicomputers)
Upvotes: 1


<issue_start>username_0: I am interested in storing accelerometer data to an SD card. Since power consumption is the main consideration of my project, it is important to do as few writes to the SD as possible, because the SD requires much current, and also takes long to be written, keeping my MCU from sleeping.

1. The data to be stored are about 50 bits of data at 10Hz, so I need to store 500c bits per second, or around 63 bytes per second. The arduino uno EEPROM is 1024 bytes, which could give me around 16 seconds of data stored before having to access my SD card. However I have seen that the EEPROM has limited write cycles (100000). So each byte can be written 100000 times, which gives us a total of 1000\*100000=100000000 bytes to be written.As a result, with writing there 63 bytes per second, that would give me 1587301 seconds=441hours=18days of EEPROM lifetime, which is unacceptable. Is this correct?
2. If (1) is correct and using internal eeprom is not a possible solution, what other recommendations do you have? Is there an alternative to SD storage, that requires less power and less writing time, so that it is cheaper power-wise? The total storage should be around 200MB.<issue_comment>username_1: Regarding 1, it's true that EEPROM has limited write cycles. Mostly it can be much more, but it's only guaranteed upto that number, so I can imagine you don't want taking the risk to be lucky.

Regarding 2, other solutions could be external SRAM, which can be much more than just 1 KB, but also adds some extra components, thus cost and more important power. When that SRAM is full (can be many KBs), you can transfer it to the SD card.

Another (added) improvement you might think of (if you did not already) is data compression (trying to store the 50 bits in less bits), but this will cost some 'computing' power.
Upvotes: 2 <issue_comment>username_2: To start with power consumption rules an Arduino UNO out so you will need some device capable of (deep) sleep mode. Devices like ESP8266 or ESP32. The table below shows the differences between each mode (information from the ESP8266 datasheet).

```
Item                 Modem-sleep        Light-sleep       Deep-sleep
Wi-Fi                   OFF          OFF            OFF
System clock             ON         OFF             OFF
RTC                     ON          ON              ON
CPU                     ON          Pending         OFF
Substrate current     15 mA        0.4 mA          ~20 uA
Avg. current (DTIM = 1) 16.2 mA     1.8 mA            –
Avg. current (DTIM = 3) 15.4 mA     0.9 mA            –
Avg.current (DTIM = 10) 15.2 mA     0.55 mA

```

These modules have around 4MB flash which yoi could use for storage of data (SPIFFS/LittleFS) so 1MB for programs and 3MB for on board storage, after that you save to SD and fill up the onboard FS again or you send the data via WLAN to an online storage or database or to a server in your network (depending on your scenario) These devices cost as much as an Arduino UNO clone (5-7$) and can be programmed with the same IDEs as Arduinos and in the same (extern C/)C++ derivate. So if power consumption is an issue look at those IoT devices
Upvotes: 0


<issue_start>username_0: This code runs without issues, scoped and seen from serial output:

```
#include

void setup() {
 // put your setup code here, to run once:
 Serial.begin(115200);
 Wire.begin();
 Wire.onReceive(receiveEvent);

 while (!Serial);
}

void loop()
{
 Serial.println("1");
 Wire.beginTransmission(8);
 Serial.println("2");
 Wire.write(0x1);
 Serial.println("3");
 delay(100);
 Wire.endTransmission();
 delay(100);
 Serial.println("4");
 delay(500);
}

void receiveEvent(int howmany)
{
 delay(100);
}

```

This one hangs on Wire.endtransmission():

```
#include

void setup() {
 // put your setup code here, to run once:
 Serial.begin(115200);
 Wire.begin(10);
 Wire.onReceive(receiveEvent);

 while (!Serial);
}

void loop()
{
 Serial.println("1");
 Wire.beginTransmission(8);
 Serial.println("2");
 Wire.write(0x1);
 Serial.println("3");
 delay(100);
 Wire.endTransmission();
 delay(100);
 Serial.println("4");
 delay(500);
}

void receiveEvent(int howmany)
{
 delay(100);
}

```

The problem starts as soon as I assign an address in Wire.begin(). As I understand, a slave is also allowed to send data and temporarily becoming a master when addressing another device.<issue_comment>username_1: You can write your own python script that prints received serial output. By using try/except in a loop you can "pause" your serial monitor while uploading is in progress.

I did the same a while ago using `pyserial` on linux. I'd like to share it, but at the moment I have no access to my other machine. I can post it later if you want.
Upvotes: 1 <issue_comment>username_2: >
> (using screen, socat and others) but none of them deals with the question how to not block the port.
>
>
>

>
> Other pointers on how to solve the issue are appreciated!
>
>
>

I say:

>
> Virtually all hardware problems can be solved with software. But, sometimes, the $50000 software problem can be solved with the $2 hardware solution.
>
>
>

This is one of those cases. [Buy a CP2102 6-pin serial UART USB adapter for < $2 on Ebay](https://www.ebay.com/sch/i.html?_from=R40&_trksid=p2380057.m570.l1313&_nkw=serial%20uart%206%20pin&_sacat=0), or [for < $10 on Amazon](https://amzn.to/33JB1Jf), to provide a second serial interface to the same Arduino (both connected to the same hardware UART built in to the Arduino's ATmega328 mcu). Let the main USB serial interface handle code uploads to the Arduino. Let this 2nd, external UART handle READ-ONLY from the Arduino!

Plug it in:

```
Arduino     CP2102 USB 6-pin UART
-------     ---------------------
Tx          Rx
GND         GND

```

Done. Do NOT plug in the CP2102 `Tx` to anything.

Now, use [`picocom`](https://github.com/npat-efault/picocom) (one of my favorites), `screen`, or [my crude datalogging Python serial terminal I wrote here (eRCaGuy\_PyTerm)](https://github.com/ElectricRCAircraftGuy/eRCaGuy_PyTerm), or a 2nd instance of the Arduino IDE with the Serial Monitor, or any other serial terminal for that matter, to read from the CP2102 while the Arduino's built-in USB adapter does code uploading.

Two serial interfaces to the same pins on the Arduino: one does Tx/Rx to/from the Arduino, while the other does only Rx to read from the Arduino.

I use a 2nd UART like this all the time as a trick to allow me to read the data from the Arduino into one **Serial Monitor** in one instance of the Arduino IDE so I can *see the numbers,* and I use the external CP2101 USB adapter to *read the same exact data from the Arduino* into the **Serial Plotter** of another instance of the Arduino IDE so I can see the *live, plotted graphs!*

It's amazing how well this works. Quick hack. Easy solution.

---

Note: to you use my [eRCaGuy\_PyTerm](https://github.com/ElectricRCAircraftGuy/eRCaGuy_PyTerm) Python serial terminal, first set all your serial parameters inside the `user_config.py` file, then run `python3 serial_terminal.py` to run the program. It is a 2-way serial terminal, *with datalogging*. It works quite well. I really should improve its readme and post some examples someday.
Upvotes: 3 [selected_answer]


<issue_start>username_0: I purchased [these slide switches](https://rads.stackoverflow.com/amzn/click/com/B007QAJUUS) recently because I want to use them in my project:

[![enter image description here](https://i.stack.imgur.com/nq9Jz.jpg)](https://i.stack.imgur.com/nq9Jz.jpg)

But I don't know what to connect up the three pins to and I can't find any information about them online. Nor can I find sample code. Can someone show me how to wire them up and provide sample code please? I just want to be able to check their state and save it as a boolean variable.<issue_comment>username_1: Since it has two possible positions, and three pins, you have a connection between pin 1 and 2 when position 1 is selected, and between pin 1 and 3 when position 2 is selected.
As BSF comment below, the middle pin is common. This means it will be connected to the outside pins depending on where the switch is moved towards.

However, you always can verify this, in the following way:

To find out which is pin 1, pin 2 and pin 3, use a multimeter. Set it to continuity mode, or if you don't have that mode, to resistance mode, and put the red/black probes to two random pins. Check if the resistance is 0, in that case you know those two pins will be connected when position 1 is selected. If there is resistance, try other pins with the probes, until you know which are connected.

Than switch the position, and do it again.

Instead of a multimeter you also can 'hardwire' it to e.g. 5V -> pin 1, pin 2 -> resistor of 220 ohm -> LED -> GND
And change pin 1 and pin 2 until you found which pins connect for which positions.

To use it for you Arduino, check for a normal simple switch example, but these are two in one, one for each position.
Upvotes: 2 <issue_comment>username_2: These switches are actually a lot more simple than you would think. You have two positions, but you really only care about one of them, since if it's not in that position it must be in the other.

The central pin is the common, and when slid to one side it connects that central pin to the corresponding outside pin.

So you just use the central pin and *one* of the outside pins as if it were any other on-off switch or pushbutton. Treat it *exactly* the same (pullup resistor, which may be internal to the AVR chip, and connect the IO pin to ground through the switch).

If it's "on" (reads LOW) then the switch is in one position. If it's "off" (reads HIGH) then it's in the other position.

The only times you'd want to use both outer pins is if you were wanting to direct a signal to one of two different places, or select between two different incoming signals, or if the switch were a "3 position on-off-on" switch where it can be in either outer position or *neither* position (centre off), in which case you treat it as two separate switches, but with a common central pin that connects both to ground.
Upvotes: 1 <issue_comment>username_3: As others have said, this is a SPDT (Single Pole Double Throw) switch. The center pin is common. When the switch is slid one way, it connects the center pin to the outer pin on that side. When you slide the switch the other way, it connects the center pin to the opposite outer pin.

See the link about SPDT switches Edgar provided in his comment: <http://www.learningaboutelectronics.com/Articles/What-is-a-single-pole-double-throw-switch-SPDT>

That explains these switches pretty clearly.

Connect the center pin of the switch to a digital pin on your Arduino. Connect one of the outer pins to ground.

Set the digital pin on the Arduino to `INPUT_PULLUP` mode.

Then, when you read the digital state of the pin, if it is LOW, the switch is closed. (Slid to the side of the pin you attached to ground.)
Upvotes: 3 [selected_answer]


<issue_start>username_0: I'm trying to make my LCD screen brighter, can someone can help?

These are the code and the connections:

```cpp
//LCD
#include
int Contrast=75;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

//LED
int LdrPin = A0; // the cell and 10K pulldown are connected to a0
int LdrValue = 0; // the analog reading from the sensor divider
int LedPin = 10; // connect Red LED to pin 11 (PWM pin)
int LedBrightness;

//כתום
int LdrPin2 = A0; // the cell and 10K pulldown are connected to a0
int LdrValue2 = 0; // the analog reading from the sensor divider
int LedPin2 = 9; // connect Red LED to pin 11 (PWM pin)
int LedBrightness2;

//צהוב
int LdrPin3 = A0; // the cell and 10K pulldown are connected to a0
int LdrValue3 = 0; // the analog reading from the sensor divider
int LedPin3 = 8; // connect Red LED to pin 11 (PWM pin)
int LedBrightness3;

//serial monitor
char rx\_byte = 0;
//random
long randNumber;

void setup()
{
 //אתחול LCD
 analogWrite(6, Contrast);
 lcd.begin(16, 2);

 //אתחול LED
 pinMode(LdrPin, INPUT);
 pinMode(LedPin, OUTPUT);
 Serial.begin(9600);

 pinMode(LdrPin2, INPUT);
 pinMode(LedPin2, OUTPUT);
 Serial.begin(9600);

 pinMode(LdrPin3, INPUT);
 pinMode(LedPin3, OUTPUT);
 Serial.begin(9600);

 //serial monitor
 Serial.begin(9600);

 //random אתחול
 Serial.begin(9600);
 randomSeed(analogRead(0));
}

void loop()
{
 // lcd.setCursor(2, 0);
 // lcd.print("Good Morning");

 LdrValue = analogRead(LdrPin);
 //Serial.print("LDR reading = ");
 //Serial.println(LdrValue); // print the raw analog reading
 LedBrightness = map(LdrValue, 679, 6, 255, 0);

 if (Serial.available() > 0) // is a character available?
 {
 rx\_byte = Serial.read(); // get the character
 }
 //check if morning and show good morning on thr LCD
 if (LdrValue == 679 && rx\_byte == '7')
 {
 lcd.setCursor(2, 0);
 lcd.print("Good Morning!");
 //random 50% order of lights
 randNumber = random(0, 2);
 Serial.print(randNumber);
 if (randNumber == 1)
 {
 //אדום
 for (int i=0; i<8; i++)
 {
 digitalWrite(LedPin, HIGH);
 delay(1000);
 digitalWrite(LedPin, LOW);
 delay(1000);
 //led start working on red
 lcd.setCursor(2, 0);
 lcd.print("working on");
 lcd.setCursor(2, 1);
 lcd.print("red");
 }
 //כתום
 for (int i=0; i<4; i++)
 {
 digitalWrite(LedPin2, HIGH);
 delay(1000);
 digitalWrite(LedPin2, LOW);
 delay(1000);
 //led start working on orange
 lcd.setCursor(2, 0);
 lcd.print("working on");
 lcd.setCursor(2, 1);
 lcd.print("orange");
 }

 //צהוב
 for (int i=0; i<5; i++)
 {
 digitalWrite(LedPin3, HIGH);
 delay(1000);
 digitalWrite(LedPin3, LOW);
 delay(1000);
 //led start working on yellow
 lcd.setCursor(2, 0);
 lcd.print("working on");
 lcd.setCursor(2, 1);
 lcd.print("yellow");
 }
 } else
 {
 //צהוב
 for (int i=0; i<5; i++)
 {
 digitalWrite(LedPin3, HIGH);
 delay(1000);
 digitalWrite(LedPin3, LOW);
 delay(1000);
 //led start working on yellow
 lcd.setCursor(2, 0);
 lcd.print("working on");
 lcd.setCursor(2, 1);
 lcd.print("yellow");
 }

 //כתום
 for (int i=0; i<4; i++)
 {
 digitalWrite(LedPin2, HIGH);
 delay(1000);
 digitalWrite(LedPin2, LOW);
 delay(1000);
 //led start working on orange
 lcd.setCursor(2, 0);
 lcd.print("working on");
 lcd.setCursor(2, 1);
 lcd.print("orange");
 }

 //אדום
 for (int i=0; i<8; i++)
 {
 digitalWrite(LedPin, HIGH);
 delay(1000);
 digitalWrite(LedPin, LOW);
 delay(1000);
 //led start working on red
 lcd.setCursor(2, 0);
 lcd.print("working on");
 lcd.setCursor(2, 1);
 lcd.print("red");
 }
 }
 } else
 {
 lcd.setCursor(2, 0);
 lcd.print("Good night!");
 }
}

```

[![enter image description here](https://i.stack.imgur.com/8NbnG.jpg)](https://i.stack.imgur.com/8NbnG.jpg)<issue_comment>username_1: At 115200 baud you can send 11520 characters per second. At 20 bytes per packet you can send 576 packets per second. That's 1,736µs per packet.

That's assuming zero wait between bytes. That's not going to happen.

Your measurement of 70µs will just be the time taken to place data into the transmit buffer, and has nothing to do with how long the transmission itself takes.

Roll all that together and the value of 2,500µs per packet is not unreasonable.

To transmit faster you will simply have to run at a faster baud rate. If you're getting 2500µs per packet currently and a packet takes 1736µs (call it 1,750 for simplicity) then there's about a 750µs overhead per packet to do the actual work of sending the data from the buffer. I'll assume this is a fixed value, though with no knowledge of how the STM32F1 UART works it may not be.

If you want <1000µs then that leaves you about 250µs of time to fit the packet into. That means an equivalent of 4,000 packets per second, or 80,000 bytes per second, or a baud rate of 800,000baud.

1 MBaud is more than possible, and is a good standard baud rate number that most things can cope with. So raising your baud rate to 1,000,000 *should* allow the communication to happen fast enough.
Upvotes: 2 <issue_comment>username_2: I tested a lot of baud rates on Arduino Unos, including cheap Chinese models, and decided to use a default 115200 for my DaqPort system (<https://www.daqarta.com/dw_rraa.htm>). I had found problems, like the system hanging after a second or so at 150000 baud, and didn't want to have my users run into issues that would be hard to troubleshoot.

So I'm wondering if you can reduce the bytes you need to send. Do you really need to send floats? I'm thinking 4 bytes for the data and 4 for the time would give ample resolution for almost anything, and I can't (off the top of my head anyway) think of a sensor type with more than 32-bit resolution. Also, 32 bits of msec is nearly 50 days; if you need more than that it should be pretty easy to unwrap the times after the fact.

Just a thought...
Upvotes: 0


<issue_start>username_0: 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).<issue_comment>username_1: Pattern classes are code and variables for the current set of parameters. The code doesn't take SRAM it is executed from flash. I would instance all 24 patterns for all 4 LED strips using global two dimensional array.

Advanced version could be a pool of pattern instances allocated with 'new' but never deleted, only reused. You would only create a new pattern class instance of requested type, if there is no free pattern instance of that type in the pool.

The parameters sets could be stored in PROGMEM or in EEPROM and loaded as needed into the variables of the corresponding pattern class instance.
Upvotes: 1 <issue_comment>username_2: 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](https://en.wikipedia.org/wiki/Placement_syntax) 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.
Upvotes: 3 [selected_answer]<issue_comment>username_3: When I need dynamically allocate memory, I generally pre-allocate a pool of memory blocks, each sufficiently large for the maximum size request I'll handle. Then, Whether the app requests 1 byte or MAXSIZE bytes, it gets a pointer to the *first available* one of those MAXSIZE blocks in the pool. `free()`ing such a block works just as you'd expect. Since all allocations are the same size, and no more memory is ever taken from the real heap, the pool doesn't have to (and can't, in my implementation) grow.

If this is the only dynamically allocated memory for your application, you can re-write `new()` and `delete()` to use your pool-allocator, or, if `new()` and `delete()` are implemented as wrappers around `malloc()` and `free()`, just replace those more primitive ones with the pool-based `malloc()` and `free()`.
Upvotes: 1 <issue_comment>username_4: Since you only need four objects at any given time, it would be wasteful
to statically allocate 4×24 objects, as you only really need four times
the size of the largest object. You can still use static allocation by
using an array of unions: each cell of the array will then be large
enough to store the largest possible pattern.

There may be more elegant solutions, but the simple approach is to use a
tagged union, i.e. a struct holding both a union and an extra variable
telling you what data type the union is actually holding. Beware that
there are [limitations on what type of objects you can put in an
union](https://en.cppreference.com/w/cpp/language/union). You should be safe if the actual classes have trivial
do-nothing constructors.

Below is a simplified example with two classes that each hold only a
number, either an `uint8_t` or a `uint16_t`:

```cpp
class Pattern
{
public:
    virtual void process();
};

class Pattern8 : public Pattern
{
public:
    void process() { Serial.println(8000 + param); }
    void set_param(uint8_t param8) { param = param8; }
private:
    uint8_t param;
};

class Pattern16 : public Pattern
{
public:
    void process() { Serial.println(16000 + param); }
    void set_param(uint8_t param16) { param = param16; }
private:
    uint16_t param;
};

// This is the tagged union.
struct AnyPattern : public Pattern
{
    AnyPattern() {}  // must be explicitly defined
    void process() {
        switch (type) {
            case TYPE8: pattern8.process(); break;
            case TYPE16: pattern16.process(); break;
        }
    }
    enum { TYPE8, TYPE16 } type;
    union {
        Pattern8 pattern8;
        Pattern16 pattern16;
    };
};

void setup() {
    AnyPattern patterns[2];
    patterns[0].type = AnyPattern::TYPE8;
    patterns[0].pattern8.set_param(21);
    patterns[1].type = AnyPattern::TYPE16;
    patterns[1].pattern16.set_param(42);
    Serial.begin(9600);
    patterns[0].process();
    patterns[1].process();
}

void loop(){}

```
Upvotes: 1


<issue_start>username_0: ```

#include "Keypad.h"

char Incoming_value = 0;
String password = "<PASSWORD>";
String input = "";
const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6,7,8,9}; //connect to the column pinouts of the keypad

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

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

void loop()
{
  if (Serial.available() > 0)
  {
    Incoming_value = Serial.read();
    Serial.print(Incoming_value);
    Serial.print("enter value");
    if (Incoming_value == '1') {
      digitalWrite(13, HIGH);
      Serial.print("ON");
    }
    else if (Incoming_value == '0') {
      Serial.print("OFF");
      digitalWrite(13, LOW);
    }
  }
  // Read the pushed button
  char key = keypad.getKey();
  input = input + key;
  // just print the pressed key
  if (key) {
    Serial.println(key);
  }
  if(key == '*' ){
    Serial.println(input);
    if( input == password){
      digitalWrite(13, HIGH);
    }
  }
  if(key == '#'){
    digitalWrite(13, LOW);
    input = "";
  }

/*
  // this checkes if 4 is pressed, then do something. Here  we print the text but you can control something.
  if (key == '4') {
    Serial.println("Key 4 is pressed");
          digitalWrite(13, HIGH);
      Serial.print("ON");
  }
    if (key == '5') {
    Serial.println("Key 5 is pressed");
          digitalWrite(13, LOW);
      Serial.print("ON");
  }
  */
}

```

when print input variable i get strange text like

>
> ⸮⸮⸮⸮⸮⸮⸮;⸮⸮ߵ⸮⸮⸮⸮u⸮⸮⸮⸮⸮⸮?/}⸮⸮⸮⸮⸮⸮~⸮⸮⸮⸮⸮-d
>
>
>

what i can do ?<issue_comment>username_1: **PS**: @lurker's suggestion in the comments - check the baud rate setting in your serial monitor as well.

**EDIT**: I admit that the code in the previous version of this answer was foolishly typed out by me due to lack of patience, so I'll make up for my mistake(not in code, but as a full answer).

First of all, I didn't understand what you wanted to do with the `Incoming_value` variable in your sketch, so I'm not gonna talk about it; I'd suggest adding a sufficiently small delay at the end of the code in the loop. This should provide the serial port some time to handle the incoming data and stop printing the confusing output (perhaps; just because delays make your microcontroller wait for a while to get things done elsewhere , especially where the reception of data is slow and thus avoid collisions)

Also note that I am not a CS student or an electronics geek, but I am speaking from my guesswork. Any correction is accepted.
Upvotes: 1 <issue_comment>username_2: First of all you have to make sure, that you select the same baudrate in the Serial Monitor, that you used in your sketch with `Serial.begin()`. This error is very common and garbage values is the symptom of this.

But your code also has problems. You have the `input` variable of type `String`, which should hold the user input for comparison with the password. Directly after getting the key, you are appending this key to the string. You are assuming here, that `keypad.getKey()` is waiting for the user to actually press a key and then return that. But this is not the case. `keypad.getKey()` will return `NO_KEY`, when the user currently isn't pressing a key. This is defined in the `Keypad` library as `'\0'` (the null character), which marks the end of a string. Your code runs very fast, so you are adding more and more null characters to your string. Your strings gets bigger and bigger, filling your RAM very fast.

**How to solve this:** You should only use the return value of `keypad.getKey()`, if a key was actually pressed. Put all the code after it in an if statement, checking for `NO_KEY`:

```
// Read the pushed button
char key = keypad.getKey();
if(key != NO_KEY){
    input = input + key;
    // just print the pressed key
    if (key) {
        Serial.println(key);
    }
    if(key == '*' ){
        Serial.println(input);
        if( input == password){
            digitalWrite(13, HIGH);
        }
    }
    if(key == '#'){
        digitalWrite(13, LOW);
        input = "";
    }
}

```
Upvotes: 3 [selected_answer]


<issue_start>username_0: I'm interfacing a 3.3 V device (a GPS module with a serial interface) to a 5 V Arduino Nano. The circuit I am using is this:

![schematic](https://i.stack.imgur.com/1ppnF.png)

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2f1ppnF.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)

I don't have the [GPS Module](https://proto-pic.co.uk/product/neo-6m-gps-module-for-arduino-with-large-antenna/) connected at the moment and have added LED D1 and R2 to visualise the Arduino TX signal (which is currently just setting TX GPIO pin high and low on a 1 second cycle). I am measuring the voltage at NODE1 with a DMM.

My understanding is that D3 blocks the 5V high from Arduino TX and then NODE1 is pulled to 3.3 V by R1. When Arduino TX is low (0 V) D3 conducts and pulls NODE2 to 0 V.

What I measure at NODE1 is 3.1 V and 0.8 V. Am I right in thinking that ...

1. The difference between 3.3 and 3.1 is simply the voltage drop across R1 due to the load of my LED and 5 K resistor. The RX input of the GPS module will have some similar effect.
2. The difference between 0.8 V and 0.0 V is mostly due to the forward voltage of the 1N4148? Is there significant contribution from the ATMega328P GPIO port circuitry or elsewhere?
3. This is pretty much OK and as expected.<issue_comment>username_1: >
> The difference between 3.3 and 3.1 is simply the voltage drop across R1 due to the load of my LED and 5 K resistor.
>
>
>

Correct.

>
> The RX input of the GPS module will have some similar effect.
>
>
>

No, the RX will have little to no effect. It is "high impedance" - looking to the circuit like a very small capacitor and very large resistor in series to ground. Negligible to your circuit.

>
> The difference between 0.8 V and 0.0 V is mostly due to the forward voltage of the 1N4148?
>
>
>

Yes. The datasheet shows the forward voltage can be up to 1V.

>
> Is there significant contribution from the ATMega328P GPIO port circuitry or elsewhere?
>
>
>

No.

>
> This is pretty much OK and as expected.
>
>
>

It is.

---

Now my comments:

* You should use a larger pullup and isolate your LED (if you want to keep it) with a BJT or MOSFET so it doesn't load the circuit. That will reduce the current and thus the forward voltage drop over the diode slightly.
* You should use a *Schottky* diode to considerably reduce the forward voltage drop even further. These also switch faster allowing for higher baud rates.
Upvotes: 3 [selected_answer]<issue_comment>username_2: That is correct. The most reliable solution is to use a level shifter. They are inexpensive and generally come with more than 1 channel. Use one of the additional channels to drive your led. You are reducing your logic low to 0.32 volts. Typically the threshold is 40% of VCC or 1.32 volts. - 1 volt (worse case) for the 4148 uses almost all of your marjin. That can be reduced even further by loads on the pins. The level shifter is one small board, not a handful of parts to connect which increases your chance of errors but it will help your debugging skills.
Upvotes: 2


<issue_start>username_0: I want to keep Ubuntu but remove Windows.<issue_comment>username_1: If you installed Ubuntu in a separate partition you can easily format the drive with Windows.
After that remove Windows entry from grub config.

If you use Wubi you can do one of these:

* Copy you user home folder to save most of settings.
* Use OneConf from Maverick.

And reinstall Ubuntu after that.
Upvotes: 2 <issue_comment>username_2: Assuming you have installed Ubuntu on a separate partition, all you have to do is remove your Windows partition and remove the Windows option from your GRUB boot menu.

1. Make sure your backups of your documents (and other important files, such as ebooks, videos, music, and so forth) are current. If you are going to expand the Ubuntu partition to take up the space freed by removing your Windows partition, then this is especially important, as there is always some risk (though small) of data loss when performing dynamic partition resizing. However, even if you are not planning to do this, unless you are highly experienced with repartitioning, there is a significant risk that you may make a mistake (you probably will not, but if you do, you want the consequences to be minimally bad).
2. Boot from an Ubuntu live CD/DVD or live USB flash drive (as it is not considered safe to edit a physical disk's partition table from within any of the operating systems installed on the physical disk). Select `Try Ubuntu` rather than `Install Ubuntu`.
3. Use [GParted](http://gparted.sourceforge.net/), the GNOME Partition Editor, to edit the partition table on the hard disk, removing the Windows system.

	* Start GParted (`System` > `Administration` > `GParted`, or if you're using a live system of Ubuntu 11.10 or later, press the `Super`, i.e., `Windows` key, type `gparted`, and click the search result that appears).
	* Select your Windows partition (it will be of type `NTFS` and will probably have a pale green border).
	* Delete it (`Partition` > `Delete`).
	* **Optionally**, resize your Ubuntu partition to take up the freed space. You may be able to do this by selecting it (it's of type `ext4`) and using `Partition` > `Resize/Move`. However, if it is contained in an extended partition (a kind of container partition for other partitions) and the Windows partition was not contained in the extended partition, then you may need to expand the extended partition first, and then expand the Ubuntu `ext4` partition contained within it.

	While this step is optional, the space that Windows occupied will not be available to your Ubuntu system if you skip it. (However, if you just want to use the space for storage, you could create a new partition for that purpose where your Windows partition used to be, instead of expanding Ubuntu's `ext4` partition.)
	* Apply your changes (`Edit` > `Apply All Operations`).
4. Quit GParted and reboot (click the power icon at the upper-right corner of the screen and click `Restart` or `Shut Down`). Once you have booted back into the Ubuntu system installed on the hard drive, update your GRUB menu to remove the Windows option, by running `sudo update-grub` in a Terminal window (`Ctrl`+`Alt`+`T`). When you run that command, you might be prompted for your password. As you enter it, you won't see any placeholder characters (like `*`). That's OK--just type it in and press enter. After you've run that command, Windows should no longer appear as an option to select in the boot menu.

However, unless your Windows partition is seriously damaged or infected with viruses, I wouldn't recommend removing it. Instead, shrink your Windows partition, leaving space for your data plus an extra gigabyte for virtual memory (the versions of GParted that come with all currently supported Ubuntu releases are able to resize `NTFS` partitions). You never know when you'll need to use an application that only works with Windows.
Upvotes: 7 [selected_answer]<issue_comment>username_3: If you have Installed Ubuntu using WUBI then probably trying to remove windows will remove Ubuntu, as Windows installed Ubuntu into its root directory unless you haven't specified a different directory at the installation time.
Upvotes: 2 <issue_comment>username_4: Here is a graphical tool to `easily remove any OS (Windows, or Ubuntu, or else)`: [OS-Uninstaller](https://help.ubuntu.com/community/OS-Uninstaller)

![enter image description here](https://i.stack.imgur.com/laS2b.png)
Upvotes: 4


<issue_start>username_0: What steps should be taken before/during/after installation of Ubuntu on a Solid State Drive to optimize performance and ensure maximum durability of the drive?<issue_comment>username_1: I have successfully used several different techniques to improve the way Ubuntu uses the storage device, whether that be solid state or traditional drive.

For SSD's you are looking to minimise the number of times the drive is written too, as reads should not add wear to the drive.

**1) Manage the swap file**

If you do not hibernate your computer and you have ample RAM memory to run all your applications, then in theory you do not need a swap partition.

If you have a mix of SSD and hard drives, place your swap partition on the hard drives only.

**2) No Writes for Read Timestamps** (suitable for SSD's and hard drives)

Mounting your partitions with the options **noatime** and **nodiratime** will stop timestamp writes when you read files and folders. These timestamp writes are not generally required unless you use a local mail server client such as mutt. The reason this is generally a bad idea, is because every read will produce a write when updating the timestamps. This decreases the life of the SSD.

Edit your **/etc/fstab** configuration file (carefully - take a backup to be sure as breaking your fstab configuration can prevent you system from working):

```
cp /etc/fstab ~/fstab-backup
gksudo gedit /etc/fstab

```

Edit the mounting options for your partitions by adding the text noatime and nodiratime to the lines defining your root (/) and other partitions if you have them (/home) - *Note: if you have a /home partition, start with that just changing that partition if you are concerned about breaking something*

```
# / was on /dev/sda2 during installation
UUID=587e0dc5-2db1-4cd9-9792-a5459a7bcfd2 /               ext4    noatime,nodiratime,errors=remount-ro 0       1

# /home was on /dev/sda3 during installation
UUID=2c919dc4-24de-474f-8da0-14c7e1240ab8 /home           ext4    noatime,nodiratime,defaults        0       2

```

You will need to reboot your machine before these changes take effect

**3) Minimising writes from the OS and applications**

Assuming that you are not running a mission critical product server, most people do not look at logs should something go wrong (especially as serious errors are rare for most Ubuntu users). Therefore you can configure Ubuntu so all logs get written to RAM memory rather than the SSD.

*Note: only make the following changes when you have installed all software you are going to use (especially things like Apache web server), otherwise you may experience some issues with missing directories in /var/log*

For background to this approach, see [prolonging the life of your flash drive on ubuntu-eee.com](http://www.ubuntu-eee.com/wiki/index.php5?title=How_to:_Reduce_Disk_Writes_to_Prolong_the_Life_of_your_Flash_Drive)

Open **/etc/fstab** with an editor (assuming you have backed up the /etc/fstab file)

```
gksudo gedit /etc/fstab

```

Add the following lines at the end of the fstab file and save:

```
# Uncomment these after all server based applications installed - eg. apache
#tmpfs /tmp tmpfs defaults,noatime,mode=1777 0 0
#tmpfs /var/tmp tmpfs defaults,noatime,mode=1777 0 0
#tmpfs /var/log tmpfs defaults,noatime,mode=0755 0 0
#tmpfs /var/log/apt tmpfs defaults,noatime 0 0
# none /var/cache unionfs dirs=/tmp:/var/cache=ro 0 0

```

You will need to reboot your machine before these changes take effect

See also:

* [How to enable TRIM?](https://askubuntu.com/questions/18903/how-to-enable-trim)
Upvotes: 8 [selected_answer]<issue_comment>username_2: ### SSD Life

Generally I wouldn't bother - the worries about SSD life are overblown. You can read this [detailed article about why you really shouldn't worry](http://www.storagesearch.com/ssdmyths-endurance.html). In short the circuitry inside modern SSDs manages wear-levelling for you, and they know how to do it far better than you.

In the article is a calculation of the life of an SSD that is receiving writes at a continuous rate of 80M/s. The life is **51 years**. That is based on 2007 technology - SSD life will be longer now. And you almost certainly don't write to your SSD at 80M/s 24 hours a day.

### SSD Performance

However performance degradation over time can be a problem, and [TRIM](https://en.wikipedia.org/wiki/Trim_(computing)) is the solution. There are two options

* automatic/online TRIM, aka discard
* manual TRIM

You have to [enable automatic TRIM yourself](https://askubuntu.com/a/19480/150) . (Basically you add the `discard` option to your mount options, provided you are using ext4.) I have found a blog post reporting that [the discard option slows down your system when deleting files](https://patrick-nagel.net/blog/archives/337).

You can occasionally do it manually (or in a cron job) using [fstrim](http://manpages.ubuntu.com/manpages/precise/en/man8/fstrim.8.html). If you just have one partition then all you need to do is:

```
sudo fstrim /

```

Note that fstrim is only available in 11.10 and newer. For older systems you will need the `wiper.sh` script. I found the script at `/usr/share/doc/hdparm/contrib/wiper.sh.gz` on my system.

If you're wondering, the problem that TRIM solves, as [described by Wikipedia](http://en.wikipedia.org/wiki/TRIM#Flash_drive_specific_issues), is:

>
> SSDs store data in flash memory cells that are grouped into pages, with the pages (typically 4 kB each) grouped together into blocks (typically 128 pages per block, totaling 512 kB). NAND flash memory cells can only be directly written to when they are empty. If they are considered to contain data, the contents first need to be erased before a write operation can be performed reliably. In SSDs, a write operation can be done on the page-level, but due to hardware limitations, erase commands always affect entire blocks. As a result, **writing data to SSD media is very fast as long as empty pages can be used, but slows down considerably once previously written pages need to be overwritten**. Since an erase of the cells in the page is needed before it can be written again, but only entire blocks can be erased, an overwrite will initiate a read-erase-modify-write cycle: **the contents of the entire block have to be stored in cache before it is effectively erased on the flash medium, then the overwritten page is modified in the cache so the cached block is up to date, and only then is the entire block (with updated page) written to the flash medium**. This phenomenon is known as write amplification.
>
>
>
Upvotes: 7 <issue_comment>username_3: **4) enable automatic TRIM**

If your SSD supports it, you should also enable automatic TRIM (as described [here](https://askubuntu.com/questions/18903/how-to-enable-trim/19480#19480))
Upvotes: 3 <issue_comment>username_4: There are several points:

**Alignment:**

What is often pointed out is the right [alignment](https://wiki.archlinux.org/index.php/SSD#Partition_Alignment) of the partition. This should be equal to the block size of the SSD. Play safe and make your partitions aligned to MiB boundaries. Note that you can't do this with the Ubuntu installer's partition tool (which uses MB not MiB), but you can boot the live CD, use Gparted (which uses MiB), then click Install to use the partitions you set up.

**The right scheduler:**

A important point is the [scheduler](https://wiki.archlinux.org/index.php/SSD#I.2FO_Scheduler) wich should be `noop`. You can set this scheduler via kernelparameter `elevator=noop` or via a entry `echo noop > /sys/block/sda/queue/scheduler` in you rc.local.

**Mountflags:**

I would recommend `noatime` and `discard`

**Tmpfs**

To put tmp on a ramdisk can increase the life time of the ssd.
To use this put the following line in you fstab: `none /tmp tmpfs defaults 0 0`

Generally if you want to dive deeper into this topic I would recommend [this](https://wiki.archlinux.org/index.php/SSD) excellent wiki-article.
Upvotes: 4 <issue_comment>username_5: I suggest to place only those things which are read at boot time on the SSD any maybe applications which require much time to load.Data and logs and other uncritical things I would locate on a normal HDD.Also you could setup your ubuntu to only load a big initramfs from SSD at boot time and not write back changes to ssd.This has the benefit, that changes to this partition are not persistent which is sth like a protection for your boot system.Therefor you would need much more RAM of course.

I would e.g. place the partitions
/, /etc, /usr, /boot, /lib 32/64 on SSD while sth like

/opt, /bin, /sbin, /root, /home and even swap (increase RAM!!!) on HDD

[Wikipedia](http://en.wikipedia.org/wiki/Solid-state_drive#SSD-optimized_file_systems) says:

>
> The Linux kernel supports the TRIM function starting with version 2.6.33. The ext4 file system is supported when mounted using the "discard" parameter. The most recent disk utilities (and therefore installation software that make use of them) also apply proper partition alignment.
>
>
>

For backups there are many ways, simplest of which is (r)sync plus cron job.
Upvotes: 0 <issue_comment>username_6: Fast tuning course for your SSD on Ubuntu:

**filesystem**

Arch wiki [mentions](https://wiki.archlinux.org/index.php/Solid_State_Drives#Choice_of_Filesystem) few preferable options for SSD file system - one of them is unstable, others are *ext*\* ones. I assume *ext4* is one of the best picks.

Note: In case of *ext4* you may want to use `discard` mount option.

**fstab**

```
#
proc /proc proc nodev,noexec,nosuid 0 0
tmpfs /tmp tmpfs nodev,nosuid,noatime,mode=1777 0 0
/dev/sda1 / ext4 defaults,noatime,discard,errors=remount-ro 0 1
/dev/sda2 /home ext4 defaults,noatime,discard,user\_xattr 0 2
/dev/sda3 /windows ntfs defaults,noatime,discard,umask=007,gid=46 0 0

```

Few important things here are:

* For systems with >=2 gigs of memory, locating /tmp in the RAM is desirable.
* No `swap` partition. Nowadays it's needed only for hibernation, since modern machines has pretty big amount of RAM.
* `noatime` and `discard` options. Info is [here](https://wiki.archlinux.org/index.php/Solid_State_Drives#Mount_Flags).

**scheduler**

Consider switching from the default scheduler, which under most Linux distro's is cfq (completely fair queuing), to the noop or deadline scheduler for an SSD. Using the noop scheduler, for example, simply processes requests in the order they are received, without giving any consideration to where the data physically resides on the disk. This option is thought to be advantageous for SSDs since seek times are identical for all sectors on the SSD.

Add following to */etc/rc.local*:

```
# SSD performance tuning
echo noop > /sys/block/sda/queue/scheduler

```

**info**

[one](https://wiki.archlinux.org/index.php/Solid_State_Drives) [two](http://itezer.com/blog/ubuntu-linux/125-four-tweaks-for-using-ubuntu-with-ssd.html)
Upvotes: 4 <issue_comment>username_7: Ok "long story short":

1. Yes. It is like a normal hdd. [Here](https://wiki.archlinux.org/index.php/SSD) is a good overview.
2. Some special extras, that I will cover.
3. Quite good. I use it with a server.

Format as `ext4` during install, and create a small swap ~1 GB. After install edit fstab with `sudo gedit /etc/fstab` and add the following line

```
tmpfs /tmp tmpfs defaults,noatime,mode=1777 0 0

```

This will create a ramdrive for your temp files, which will lower the ageing. Also add `noatime,nodiratime,discard` to your ext4 line after defaults. This will also lower wear, and enable TRIM function. Save and reboot.
Upvotes: 2 <issue_comment>username_8: UPS is required.In the `/etc/sysctl.conf` file

```
vm.dirty_writeback_centisecs = 15000
vm.swappiness = 10

```

Find the configuration file daemon, usually `/etc/syslog.conf` или `/etc/rsyslog.d/` and all the paths of the form `/var/log/` change by writing a minus sign ("-") in front of ways.Before
mail.err

```
/var/log/mail.err

```

After

`mail.err -/var/log/mail.err`

use FS `btrfs` and use the `-o ssd` option

More <http://vasilisc.com/speedup_ubuntu_eng#speedup_fs>
Upvotes: 2 <issue_comment>username_9: It is clear that `/var/tmp` should not be in tmpfs since by definition it's content needs to be preserved beyond reboots:

* [Differences between TMP and VarTMP](http://linuxers.org/article/differences-between-tmp-and-vartmp)
Upvotes: 2 <issue_comment>username_10: I would not add this line to your fstab, var/tmp folder is meant to survive reboots, and that could cause issues for you.

```
tmpfs /var/tmp tmpfs defaults,noatime,mode=1777 0 0

```

When I configure new system I leave all the tmp folder commented out this way if anything happens I can check the logs and stuff. Then once I have the main system setup I will un-comment them, but I never add the above line, here is what I use:

```
tmpfs /tmp tmpfs defaults,noatime,mode=1777 0 0
tmpfs /var/log tmpfs defaults,noatime,mode=0755 0 0
tmpfs /var/log/apt tmpfs defaults,noatime 0 0

```

And if I am having any issues with my system I comment those out to be able to check everything even after a reboot or forced reboot after a lockup.

Also you don't need nodiratime, noatime option takes care of both by itself.

As for TRIM, if your hw/sw support it, it's a must, I do not use discard in fstab. I create a daily cron, because my PC is always on, by doing this:

```
gksu gedit /etc/cron.daily/trim

```

Then add this to file and save (If you dont have a seperate /home partition on ssd, or have other parts that are on ssd you should get the idea how to modify this:

```
#!/bin/sh
LOG=/var/log/trim.log
echo "*** $(date -R) ***" >> $LOG
fstrim -v / >> $LOG
fstrim -v /home >> $LOG

```

Then make the file executable by:

```
sudo chmod +x /etc/cron.daily/trim

```

I also edit my rc.local like so:

```
gksu gedit /etc/rc.local

```

Add this above "exit 0" and below the last #:

```
# Modification for SSD
# you may want to add more folders to be checked/created to this list
for dir in apparmor apt ConsoleKit cups dist-upgrade fsck gdm installer news ntpstats samba speech-dispatcher unattended-upgrades; do
  if [ ! -e /var/log/$dir ] ; then
    mkdir /var/log/$dir
  fi
done

```

You can copy and paste from here so there is no errors, to the layman it looks out of whack, it is not.

I have also read that leaving 10% of your ssd drive unformatted can help extend life, that remains to be seen. I have not read that much into this so I can't vouch if it makes sense to do so.

This is the best all around guide, he did not skim around Google for a day and then come up with a guide, you should check it out [HERE](https://sites.google.com/site/easylinuxtipsproject/ssd)
Upvotes: 2 <issue_comment>username_11: There are some good info How to tweak and optimize SSD for Ubuntu, Linux Mint from <http://namhuy.net/1563/how-to-tweak-and-optimize-ssd-for-ubuntu-linux-mint.html> you might be interested in

**Use preload**

To install preload on Ubuntu, Linux Mint or debian based distributions

```
# apt-get update && apt-get install preload

```

**Turn off your swap**

To change swappiness setting:

```
$ su -
# nano /etc/sysctl.conf

```

And add this line into sysctl.conf file.

```
vm.swappiness = 10

```
Upvotes: 2 <issue_comment>username_12: [How to tweak and optimize SSD for Ubuntu, Linux Mint](http://namhuy.net/1563/how-to-tweak-and-optimize-ssd-for-ubuntu-linux-mint.html)

Enable TRIM

TRIM (Trim command let an OS know which SSD blocks are not being used and can be cleared)

Back up fstab first in case something wrong happen.

```
# cp /etc/fstab ~/fstab.bk

```

Edit fstab file

```
# nano /etc/fstab

```

Add discard to your ssd drives or partitions, after ext4

```
UUID=bef10b86-494d-41c6-aa46-af72cfba90fd / ext4 discard,errors=remount-ro 0 1
Adding noatime and nodiratime

```

noatime and nodiratime are mount options in linux for linux file system. noatime disables atime updates on file system, and nodiratime will disables atime updates on directory system. By adding noatime and nodiratime will greatly reduce ssd load means performance gains.

Edit fstab file

```
# nano /etc/fstab

```

Add noatime,nodiratime to your ssd drives or partitions, after ext4

```
UUID=bef10b86-494d-41c6-aa46-af72cfba90fd / ext4 discard,noatime,nodiratime,errors=remount-ro 0 1

```
Upvotes: 1 <issue_comment>username_13: *TRIM allows an operating system to inform an SSD which blocks of data are no longer considered in use and can be wiped internally. Trimming enables the SSD to handle garbage collection overhead, which would otherwise significantly slow down future write operations to the involved blocks, in advance.*1

In Ubuntu 14.04 a new feature has been added to the *util-linux* package that regularly trims SSDs automatically, but only Intel and Samsung SSDs have TRIM enabled by default, because some cheap SSDs can even brick themselves when running TRIM.2 The contents of `/etc/cron.weekly/fstrim` in Ubuntu 14.04:

```
#!/bin/sh
# call fstrim-all to trim all mounted file systems which support it
set -e

# This only runs on Intel and Samsung SSDs by default, as some SSDs with faulty
# firmware may encounter data loss problems when running fstrim under high I/O
# load (e. g.  https://launchpad.net/bugs/1259829). You can append the
# --no-model-check option here to disable the vendor check and run fstrim on
# all SSD drives.
exec fstrim-all

```

1<https://en.wikipedia.org/wiki/Trim_%28computing%29>

2[How is Trim enabled?](https://askubuntu.com/questions/443761/how-is-trim-enabled-in-ubuntu-14-04/443779#443779)
Upvotes: 2


<issue_start>username_0: I am not talking about `shutdown` and `reboot` commands. I want to initiate the same routine from command line that would be performed if I would press the logout/reboot/shutdown button inside the KDE desktop.<issue_comment>username_1: For KDE 5+:

```
qdbus org.kde.Shutdown /Shutdown logout
qdbus org.kde.Shutdown /Shutdown logoutAndReboot
qdbus org.kde.Shutdown /Shutdown logoutAndShutdown

```

The last option specifies which method gets called. It seems the options for KDE4 mentioned below are partially supported(reboot didnt work so I ended up using these newer methods).

Ref: [Reddit](https://www.reddit.com/r/kde/comments/ojpvwx/how_to_reboot_properly_from_the_cli/h54a2ge?utm_source=share&utm_medium=web2x&context=3)

For KDE 4:

*Note that this answer was written in 2010 for KDE 4. It may not apply to modern systems.*

```
qdbus org.kde.ksmserver /KSMServer org.kde.KSMServerInterface.logout -1 -1 -1

```

The three integer parameters are the `confirm`, `sdtype` and `sdmode` arguments to [KWorkSpace::requestShutDown](https://api.kde.org/4.x-api/kde-workspace-apidocs/plasma-workspace/html/namespaceKWorkSpace.html#a0c75f4db070a83b47f0bfc5026383aeb). Their values are explained at the top of the page. Since the page has disappeared, here are the values (still present in a [cache](https://webcache.googleusercontent.com/search?q=cache:_0W89JZwYrMJ:https://api.kde.org/4.x-api/kde-workspace-apidocs/plasma-workspace/html/namespaceKWorkSpace.html+&cd=1&hl=en&ct=clnk&gl=fr)).

```
enum ShutdownConfirm {
  ShutdownConfirmDefault = -1,
  ShutdownConfirmNo = 0,
  ShutdownConfirmYes = 1
}

```

>
> * `ShutdownConfirmDefault`:
> Obey the user's confirmation setting.
> * `ShutdownConfirmNo`:
> Don't confirm, shutdown without asking.
> * `ShutdownConfirmYes`:
> Always confirm, ask even if the user turned it off.
>
>
>

```
enum ShutdownMode {
  ShutdownModeDefault = -1,
  ShutdownModeSchedule = 0,
  ShutdownModeTryNow = 1,
  ShutdownModeForceNow = 2,
  ShutdownModeInteractive = 3
}

```

>
> * `ShutdownModeDefault`:
> Select previous mode or the default if it's the first time.
> * `ShutdownModeSchedule`:
> Schedule a shutdown (halt or reboot) for the time all active sessions have exited.
> * `ShutdownModeTryNow`:
> Shut down, if no sessions are active.
> Otherwise do nothing.
> * `ShutdownModeForceNow`:
> Force shutdown.
> Kill any possibly active sessions.
> * `ShutdownModeInteractive`:
> Pop up a dialog asking the user what to do if sessions are still active.
>
>
>

```
enum ShutdownType {
  ShutdownTypeDefault = -1,
  ShutdownTypeNone = 0,
  ShutdownTypeReboot = 1,
  ShutdownTypeHalt = 2,
  ShutdownTypeLogout = 3
}

```

>
> * `ShutdownTypeDefault`:
> Select previous action or the default if it's the first time.
> * `ShutdownTypeNone`:
> Only log out.
> * `ShutdownTypeReboot`:
> Log out and reboot the machine.
> * `ShutdownTypeHalt`:
> Log out and halt the machine.
> * `ShutdownTypeLogout`:
> Temporary brain damage.
> Don't use. Same as ShutdownTypeNone
>
>
>
Upvotes: 6 [selected_answer]<issue_comment>username_2: For any version of KDE (maybe also GNOME and others):

In KDE Control Center (KDE3.5/trinity) you can set a keyboard shortcut for "halt without confirmation" (should be a complicated one to avoid tragedy, like `Ctrl`+`Shift`+`Alt`+`Delete`) and then run `xvkbd` (virtual keyboard):

```
xvkbd -text '\C\S\A\d'

```

You can create an alias for this (e.g. `kdehalt`);

My favourite one: `sleep 1h 20m && kdehalt` or `wget "http://something" ; kdehalt`.
Upvotes: 2 <issue_comment>username_3: So I tried the answer presented by Gilles, but that only works for KDE4.

After a system-update with my graphics, I could no longer log out, reboot, or shutdown. Eventually found this command ***worked***:

```
qdbus org.kde.ksmserver /KSMServer logout 0 0 0

```

My source is from here, where they discuss it a bit more. I'm not sure about he other optoins. [Forum topic discussion KDE5 shutdown options.](https://forum.kde.org/viewtopic.php?t=88022) The above command seems to have shutdown my system gracefully. All my programs came back that were expected, in the right layout order, and I did not seem to be missing anything. If this doesn't work, please comment and I will adjust my answer but so far this is all that has worked for a graceful KDE5 shutdown when my is locked. (I obviously could have used the shutdown command or called init, but those aren't graceful.)
Upvotes: 3