Id
stringlengths
1
5
Tags
stringlengths
3
75
Title
stringlengths
15
150
CreationDate
stringlengths
23
23
Body
stringlengths
51
27.6k
Answer
stringlengths
42
31k
94667
|programming|arduino-nano|c++|
"if" condition problem / question
2023-10-27T20:16:10.900
<p>I'm new to Arduino and my question is rather theoretical. I have an Arduino Nano board (Atmega168 processor), a button, a display. I have written a button handler that does not stop code execution. My idea is: poll the button in &quot;loop&quot; cycle, and if it is pressed, perform <code>k++</code>. When <code>k</code> exceeds a specified value, perform <code>cnt++</code> and print it on the display.</p> <p>Code example №1 works correctly. I get 1 -&gt; 2 -&gt; 3 -&gt; ...:</p> <pre><code>void loop() { if (digitalRead(button_pd) == LOW) { k = k + 1; if (k &gt;= 20) { k = 0; cnt = cnt + 1; } lcd.clear(); lcd.setCursor(0, 0); lcd.print(cnt); } } </code></pre> <p>Code example №2 is incorrect. I get 16 -&gt; 27 -&gt; 40 -&gt; ... Seems like not <code>cnt</code> is printed, but <code>k</code>.</p> <pre><code>void loop() { if (digitalRead(button_pd) == LOW) { k = k + 1; if (k &gt;= 20) { k = 0; cnt = cnt + 1; lcd.clear(); lcd.setCursor(0, 0); lcd.print(cnt); } } } </code></pre> <p>Here's my program:</p> <pre><code>#include &lt;LiquidCrystal_I2C.h&gt; #define button_pd 6 LiquidCrystal_I2C lcd(0x27, 16, 2); int k = 0; int cnt = 0; void setup() { pinMode(button_pd, INPUT_PULLUP); lcd.init(); lcd.backlight(); lcd.clear(); lcd.setCursor(0, 0); lcd.print(cnt); } void loop() { // button handler } </code></pre> <p>My question is. Why examples №1 and №2 work differently?</p>
<p>Thanks. Somehow code example №3 works correctly. I have used a library for timer and simplified code from the answer above.</p> <pre><code>#include &lt;LiquidCrystal_I2C.h&gt; #include &lt;millisDelay.h&gt; // Timer #define button_pd 6 LiquidCrystal_I2C lcd(0x27, 16, 2); int k = 0; int cnt = 0; //uint8_t previous_state; // previous state of the button millisDelay d; void setup() { pinMode(button_pd, INPUT_PULLUP); lcd.init(); lcd.backlight(); lcd.clear(); lcd.setCursor(0, 0); lcd.print(cnt); } void loop() { uint8_t state = digitalRead(button_pd); if (state == LOW) d.start(300); //previous_state = state; if (d.justFinished()) { cnt = cnt + 1; lcd.clear(); lcd.setCursor(0, 0); lcd.print(cnt); } } </code></pre>
94675
|lcd|ssd1306|
Print text at any Y-value on SSD1306?
2023-10-29T07:09:19.337
<p>I'm attempting to print several rows of text, at certain Y-values, on an <a href="https://rads.stackoverflow.com/amzn/click/com/B074N9VLZX" rel="nofollow noreferrer" rel="nofollow noreferrer">SSD1306 128x64 LCD display</a>.</p> <p>I'm using the <a href="https://github.com/lexus2k/ssd1306" rel="nofollow noreferrer"><code>ssd1306</code> library by Alexey Dynda</a>. I initially wanted to use the more common LCD libraries out there, such as the <a href="https://github.com/adafruit/Adafruit_SSD1306" rel="nofollow noreferrer">Adafruit SSD1306 LCD library</a>, however it unfortunately does not appear I can set custom I2C pins for most such libraries out there, which is required as I'm using a custom board with an ESP32-WROOM-DA chip. The <code>ssd1306</code> by Dynda appears to be able to do so.</p> <p>I have the following example code, which prints 6 lines of text:</p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;ssd1306.h&quot; #include &quot;nano_gfx.h&quot; const int PIN_I2C_SCL = 16; const int PIN_I2C_SDA = 13; void LCDTextDraw(int x, int y, const char* text) { EFontStyle fontStyle; ssd1306_printFixed(x, y, text, fontStyle); } void LCDRectDraw(int x, int y, int w, int h) { ssd1306_fillRect(x, y, x + w, y + h); } void LCDScreenClear(bool fill) { ssd1306_clearScreen(); if (fill) LCDRectDraw(0, 0, 128, 64); } void LCDInit() { ssd1306_setFixedFont(ssd1306xled_font6x8); ssd1306_128x64_i2c_initEx(PIN_I2C_SCL, PIN_I2C_SDA, 0); } void setup() { Serial.begin(9600); pinMode(PIN_I2C_SCL, OUTPUT); pinMode(PIN_I2C_SDA, OUTPUT); LCDInit(); LCDScreenClear(true); LCDTextDraw(30, 0, &quot;TEST 1&quot;); LCDTextDraw(30, 10, &quot;TEST 2&quot;); LCDTextDraw(30, 20, &quot;TEST 3&quot;); LCDTextDraw(30, 30, &quot;TEST 4&quot;); LCDTextDraw(30, 40, &quot;TEST 5&quot;); LCDTextDraw(30, 50, &quot;TEST 6&quot;); } void loop() {} </code></pre> <p>With which I wish to print out 6 lines of text, each line evenly vertically spaced out by 10 pixels.</p> <p>Which produces the following output on my LCD:</p> <p><a href="https://i.stack.imgur.com/yI4gvm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yI4gvm.jpg" alt="enter image description here" /></a></p> <p>As you can see, the text rows are not evenly vertically spaced out as I wish them to be, with a large space between the <code>TEST 4</code> and <code>TEST 5</code> strings.</p> <p>After looking at the definition of the <code>ssd1306_printFixed</code> function I'm using to print out my text in the example above, it turns out that it can only print rows of text at certain fixed Y-positions:</p> <blockquote> <p>@warning ssd1306_printFixed() can output chars at fixed y positions: 0, 8, 16, 24, 32, etc.<br /> If you specify [10,18], ssd1306_printFixed() will output text starting at [10,16] position.</p> </blockquote> <p>Hence, I also tried using the <code>ssd1306_print</code> function (which uses a cursor to delineate its printing location on the screen), which doesn't have that warning in its header declaration. I replaced my <code>LCDTextDraw</code> function with:</p> <pre class="lang-cpp prettyprint-override"><code>void LCDTextDraw(int x, int y, const char* text) { ssd1306_setCursor8(x, y); ssd1306_print(text); } </code></pre> <p>However, that still produced the exact same output on my LCD, with the same spacing issues.</p> <p>What is the proper way to print text rows at any Y-value on an LCD?</p> <p>Thanks for reading my post, any guidance is appreciated.</p>
<p>Turns out using the <a href="https://github.com/adafruit/Adafruit_SSD1306" rel="nofollow noreferrer">Adafruit SSD1306 library</a> is much easier than I first thought. One just must specify the I2C pins used with <code>Wire</code>, and pass it as reference to the <code>Adafruit_SSD1306</code> constructor. Additionally, the Adafruit library doesn't appear to have the uneven vertical spacing issue.</p> <p>The equivalent code below using the Adafruit library:</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;Adafruit_GFX.h&gt; #include &lt;Adafruit_SSD1306.h&gt; const int PIN_I2C_SCL = 16; const int PIN_I2C_SDA = 13; Adafruit_SSD1306 LCD(128, 64, &amp;Wire); void LCDTextDraw(int x, int y, const char* text, byte size) { LCD.setCursor(x, y); LCD.setTextSize(size); LCD.print(text); LCD.display(); } void LCDRectFill(int x, int y, int w, int h, int color) { LCD.fillRect(x, y, w, h, color); } void LCDScreenClear(bool fill) { LCD.clearDisplay(); LCD.display(); LCD.setTextColor(WHITE, BLACK); if (fill) LCDRectFill(0, 0, 128, 64, 1); } void LCDInit() { LCD.begin(SSD1306_SWITCHCAPVCC, 0x3C); } void setup() { Serial.begin(9600); pinMode(PIN_I2C_SCL, OUTPUT); pinMode(PIN_I2C_SDA, OUTPUT); Wire.setPins(PIN_I2C_SDA, PIN_I2C_SCL); Wire.begin(); LCDInit(); LCDScreenClear(true); LCDTextDraw(30, 0, &quot;TEST 1&quot;, 1); LCDTextDraw(30, 10, &quot;TEST 2&quot;, 1); LCDTextDraw(30, 20, &quot;TEST 3&quot;, 1); LCDTextDraw(30, 30, &quot;TEST 4&quot;, 1); LCDTextDraw(30, 40, &quot;TEST 5&quot;, 1); LCDTextDraw(30, 50, &quot;TEST 6&quot;, 1); } void loop() {} </code></pre> <p>Now produces the desired result:</p> <p><a href="https://i.stack.imgur.com/V76dEm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V76dEm.jpg" alt="enter image description here" /></a></p>
94677
|arduino-uno|i2c|
Get address of a I2C transaction when multiple addresses are registered
2023-10-29T10:33:16.073
<p>I have an application polling 4 ADCs by I2C. The application shall also write on some ADC registers. In order to test it, I'd like to use a single Arduino UNO, enabling it for receiving I2C messages over 4 different addresses by masking the TWAMR register. In this way I can have 4 ADCs &quot;emulated&quot; on a single Arduino.</p> <p>When the application asks for a read to Arduino at some address, I'm able to get the value of the required address by reading the TWDR register:</p> <pre class="lang-cpp prettyprint-override"><code>void requestEvent(){ byte addr = TWDR &gt;&gt; 1; if (0x4A == addr){ // do something } else if (0x4B == addr){ // do something } // ... } void setup(){ // ... Wire.onRequest(requesEvent); } </code></pre> <p>However, when the application requests to write something to a certain ADC (with its own address), I'm not able to get the address value in the <code>onReceive(int)</code> callback:</p> <pre class="lang-cpp prettyprint-override"><code>void receiveEvent(int howMany){ byte addr = TWDR &gt;&gt; 1; // returns the first byte AFTER the address in the I2C message } </code></pre> <p>Am I doing something wrong? Is there a way to reach my goal?</p> <p>Thanks.</p> <p>Luca</p> <p><strong>Edit:</strong></p> <p>Reading the ATmega datasheet (sec. 22.9.4, p. 241), the problem with reading the TWDR register is that it contains the last byte received, that in slave receiver mode is not the address but the last data sent by the master.</p> <p>Anyway, is there any workaround for this problem?</p>
<p>Reading the TWDR register in the <code>onReceive()</code> callback doesn't give you the address because of the time, that it is called at. The <code>onReceive()</code> callback is called when all bytes have already been received and put in the <code>Wire</code> libraries internal buffer. Thus in that callback TWDR will still hold the last received data byte.</p> <p>The <code>onRequest()</code> callback on the other hand is called right after the address was received. Thus TWDR still holds the received address.</p> <p>You will need to modify the Wire library to achieve your goal. Similar to the <code>onRequest()</code> callback you can introduce a third kind of callback function, which will be executed after receiving the slave address to save the received address for later use (the address matching is still done via hardware, so you still need to mask the address via TWAMR).</p> <p>You can find the files for the Wire library inside your used core (for me the Uno uses the path ~/.arduino15/packages/arduino/hardware/avr/1.8.5/libraries/Wire). Look at line 581 of src/utility/twi.c. This is inside the TWI ISR, the <code>case</code> clause <code>TW_SR_SLA_ACK</code>, which will be executed on address receive/match. Here you can insert your callback function.</p> <p>If you want to do this in a similar handy way, that the <code>Wire</code> library does with the other callbacks, then you need to change a few other things:</p> <ol> <li><p>Insert a function pointer for this at the start of the twi.c file, right besides the other function pointers:</p> <pre><code> static void (*twi_onSlaveAddressMatch)(uint8_t); </code></pre> </li> <li><p>Add the execution of that function to the case in the ISR described above and provide the content of TWDR (shifted to eliminate the direction bit) as a parameter:</p> <pre><code> twi_onSlaveAddressMatch(TWDR &gt;&gt; 1); </code></pre> </li> <li><p>Add a function to set the callback function pointer in twi.c:</p> <pre><code> void twi_attachSlaveAddressMatchEvent( void (*function)(uint8_t) ){ twi_onSlaveAddressMatch = function; } </code></pre> </li> <li><p>Add the callback set function as a function prototype to twi.h:</p> <pre><code> void twi_attachSlaveAddressMatchEvent( void (*function)(uint8_t) ); </code></pre> </li> <li><p>In Wire.h add a function pointer for the new callback and the corresponding service function inside the <code>private:</code> section:</p> <pre><code> static void (*user_onSlaveAddressMatch)(uint8_t); static void onSlaveAddressMatchService(uint8_t); </code></pre> </li> <li><p>In Wire.h add a function to set the user callback function to the <code>public:</code> section:</p> <pre><code> void onSlaveAddressMatch( void (*)(uint8_t) ); </code></pre> </li> <li><p>In Wire.cpp add the implementation of the service function:</p> <pre><code> void TwoWire::onSlaveAddressMatchService(uint8_t address){ if(!user_onSlaveAddressMatch){ return; } user_onSlaveAddressMatch(address); } </code></pre> </li> <li><p>In Wire.cpp add the implementation of the callback setter function:</p> <pre><code> void TwoWire::onSlaveAddressMatch( void (*function)(uint8_t) ) { user_onSlaveAddressMatch = function; } </code></pre> </li> </ol> <p>Now you should be able to set a callback for the address receive in your main code and save the address for later use:</p> <pre><code>uint8_t received_address = 0; void getAddress(uint8_t address){ received_address = address; } void setup(){ ... Wire.onSlaveAddressMatch(getAddress); } </code></pre> <p>In the <code>onReceive()</code> callback you can then check for that global variable.</p> <p>Note: I have not tested or compiled this. I just looked at the logic of the Wire library and copied the way it already defines its existing callback functions.</p>
94684
|serial|esp32|
ESP32 cannot serial monitor
2023-10-30T15:00:37.870
<p>I use esp32 devkit v1 . I code follwing this picture. <a href="https://i.stack.imgur.com/TQzWS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TQzWS.png" alt="enter image description here" /></a></p> <pre class="lang-cpp prettyprint-override"><code>const int vavle = 1; int d = 1; void setup() { Serial.begin(115200); delay(2000); while (!Serial); Serial.println(); pinMode(vavle,OUTPUT); Serial.println(d); } void loop() { Serial.print(&quot;Open Vavle&quot;); digitalWrite(vavle,HIGH); delay(3000); digitalWrite(vavle,LOW); delay(1000); Serial.print(&quot;Close Vavle&quot;); } </code></pre> <p>but serial monitor has error when use serial monitor it show me square . I confirm select true board rate. you can solve this problem .</p>
<p>The GPIO1 pin you are trying to use with <code>const int vavle = 1;</code> ... <code>pinMode(vavle, OUTPUT);</code> <em>is</em> the same pin that carries serial data to the PC.</p> <p>From <a href="https://github.com/playelek/pinout-doit-32devkitv1/commit/afa2c642a8e63d73bce5ae93a75672a7755fe363" rel="nofollow noreferrer">the pinout</a>:</p> <p><a href="https://i.stack.imgur.com/hzs7s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hzs7s.png" alt="DOIT ESP32 DEVKIT V1 PINOUT with TX0/GPIO1/U0TXD pin highlighted." /></a></p> <p>Their schematic link is broken, but if you find schematic for pretty much any similar board using this module you'll see GPIO1/U0TXD connected to a serial transceiver chip which is then connected to the USB port.</p> <p>You need choose some other pin. There are <a href="https://randomnerdtutorials.com/esp32-pinout-reference-gpios/" rel="nofollow noreferrer">pin guides</a> and <a href="https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/gpio.html" rel="nofollow noreferrer">official documentation</a> containing the same details that you can use to figure out which GPIO to use. GPIO numbers 16 through 33 inclusive are all output-capable and seem to have no special requirements, so they make sense to choose from.</p>
94701
|arduino-uno|atmega328|
ATmega328 drop-in replacement with more flash memory
2023-11-01T06:05:44.840
<p>Is there a ATmega328 drop-in replacement with more flash memory?</p> <p>Needs to be 28 pin DIL to fit the socket.</p> <p>Alternatively, is there a board that has the exact dimensions and pins as an Arduino UNO, but with more flash memory?</p> <p>Everything in my project works fine, but I need more program memory. Can unfortunately not use a different board layout or size.</p>
<blockquote> <p>Is there a ATmega328 drop-in replacement with more flash memory?</p> </blockquote> <p>No</p> <blockquote> <p>Alternatively, is there a board that has the exact dimensions and pins as an Arduino UNO, but with more flash memory?</p> </blockquote> <p>Yes, but it'll be probably something with ARM (UNO R4 minima has even 5V ARM), However libraries might be an issue</p> <p>As for AVRs, there are for example AVR128DA28 but as far as I know, it's definitely not pin compatible.</p> <p>However you could use some proto board for UNO and wire it up somehow on it. (128kB, 28pin).</p> <p>Also Atmega644/1284 (in pdip 40) could be used on proto board and it's much more compatible</p>
94714
|serial|motor|code-review|
Arduino not reacting sometimes when reading serial commands
2023-11-02T02:46:53.167
<p>When I am sending hex numbers via computer to the arduino leonardo, it sometimes won't react, but the serial monitor says that it was sent. My code;</p> <pre><code> void setup() { Serial.begin(9600); pinMode(9, OUTPUT); pinMode(A0, OUTPUT); pinMode(10, OUTPUT); pinMode(11, OUTPUT); } void loop() { delay(100); // Wait for 100 millisecond(s) Serial.println(Serial.read()); if (Serial.read() == 49) { Serial.println(&quot;left&quot;); analogWrite(9, 1023); digitalWrite(A0, HIGH); analogWrite(10, 1023); digitalWrite(11, LOW); } if (Serial.read() == 50) { Serial.println(&quot;right&quot;); analogWrite(9, 1023); digitalWrite(A0, HIGH); analogWrite(10, 1023); digitalWrite(11, LOW); } if (Serial.read() == 51) { Serial.println(&quot;backwards&quot;); analogWrite(9, 1023); digitalWrite(A0, LOW); analogWrite(10, 1023); digitalWrite(11, LOW); } if (Serial.read() == 52) { Serial.println(&quot;forwards&quot;); analogWrite(9, 1023); digitalWrite(A0, HIGH); analogWrite(10, 1023); digitalWrite(11, HIGH); } if (Serial.read() == 48) { Serial.println(&quot;stop&quot;); analogWrite(9, 0); digitalWrite(A0, LOW); analogWrite(10, 0); digitalWrite(11, LOW); } } </code></pre> <p>When I send the numbers 1,2,3,4, and 0, it reads what the command does. Pins A0 and D11 are direction control for the motor controller, and pins D9 and D10 are speed.</p> <p><a href="https://i.stack.imgur.com/sEx43.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sEx43.jpg" alt="it is kinda a mess." /></a></p>
<blockquote> <pre><code>Serial.println(Serial.read()); if (Serial.read() == 49) { </code></pre> </blockquote> <p>You are doing two reads here, not one. So you are reading and displaying, and then reading a <strong>second</strong> byte (not the one you displayed).</p> <p>Much better would be:</p> <pre><code>int cmd = Serial.read(); Serial.println(cmd); if (cmd == 49) { ... do something ... } else if (cmd == 50) { .. do something else ... } </code></pre> <p>And so on.</p> <p>Also, why use numbers when you can show the ASCII characters? eg.</p> <pre><code>int cmd = Serial.read(); Serial.println(cmd); if (cmd == '1') { ... do something ... } else if (cmd == '2') { .. do something else ... } </code></pre> <p>You may also want to consider using:</p> <pre><code>if (!Serial.available()) return; </code></pre> <p>That way you don't test for serial data that does not exist.</p> <p>Why the delay?</p>
94716
|relay|switch|
How can I switch the power on/off to cut BIG currents (200A)?
2023-11-02T08:25:49.880
<p>Context: I have an off-grid cabin with PV powered 12V DC. I want to cut power to an inverter (12V DC -&gt;220V AC) when I leave by pressing a button as it draws too much in standby.</p> <p>Most relays I have seen that can be connected to the Arduino typically handle 10A. My inverter draws up to 180A@12V at full power (2000 W), which is way more than anything I have seen. How can I control the power to this inverter?</p> <p>Someone told me of hacks that utilize the fact that you get manual switches/relays that handle big current, so you can use the Arduino to control a motor pressing the physical switch, but the concept seems somewhat brittle ... Any other takes?</p> <pre><code> ┌────────────┐ │ PV array │ └──────┬─────┘ │ ┌─────┴───┐ │ Charger │ ┌─┴─────────┘ │ │ ┌────────┴──┐ ┌─────────┐ │ Batteries ├─────────┤Inverter ├────────────┐ └────────┬──┘ └─────────┘ │ │ │ │ ┌────────┴─────┐ │ │220V circuit │ ┌───┴───────────────┐ │ w/appliances│ Has │ Fuse box │ └──────────────┘ on/off │ / 12v distribution│ switch!└───────────────────┘ ┌──────────────┐ │12V appliances│ └──────────────┘ </code></pre>
<p>You might look for something like a &quot;starter relay&quot; for an engine. Those switch on 12 V and can handle currents of 150A and more. I've seen various models on the site of my favorite distributor.</p> <p><strong>Check the data sheet to make sure the relay can handle a continuous current of 180A</strong>, as many starter relays can only handle the current for short periods of time (you're not running the starter motor of an engine for more than a few seconds). Other possible types are 12V-industry-rated high-current relays. Also mentioned in a comment above: The hold-current of the relay shouldn't be to big, so you don't waste energy just for the switch.</p> <p>You might need to use a 2-step solution, to first convert the 5V output of the Arduino to 12 V to control the relay. (use a small relay for this, or just a mosfet).</p>
94719
|usb|
Getting a strange symbol when pressing buttons in a USB keyboard connected to the Arduino GIGA R1
2023-11-02T15:18:30.683
<p>I am using the following code:</p> <pre><code>#include &quot;USBHostGiga.h&quot; //REDIRECT_STDOUT_TO(Serial) Keyboard keyb; HostSerial ser; void setup() { // put your setup code here, to run once: Serial.begin(115200); while (!Serial); pinMode(PA_15, OUTPUT); keyb.begin(); ser.begin(); } void loop() { if (keyb.available()) { auto _key = keyb.read(); Serial.println(keyb.getAscii(_key)); } while (ser.available()) { auto _char = ser.read(); Serial.write(_char); } //delay(1); } </code></pre> <p>from here: <a href="https://docs.arduino.cc/tutorials/giga-r1-wifi/giga-usb" rel="nofollow noreferrer">https://docs.arduino.cc/tutorials/giga-r1-wifi/giga-usb</a></p> <p>I am using Arduino GIGA R1 on which I have connected a USB keyboard and I press buttons. I see the results on the Serial. However, I face the following problem: When I press a button, apart of the letter I get also a square next to it. For instance, let's say I press the 'A' letter. In the serial I get 'A' letter + a square symbol. When I press 'B', I get 'B' + a square symbol, etc. I am trying for 2 days to fix it, I tried to read the button as a char array with two positions and delete the [1] where the square should be, but nothing worked. The <code>auto</code> type is very strange in order to make a type casting, because the Arduino IDE continuously shows me error. I cannot find a way to remove the strange 'square' ASCII character which I take with each letter pressed...The only things I noticed is that the square ASCII character is displayed the time I release the keyboard button, and also it delays to appear when I increase the delay ms in the <code>delay(...);</code> command. Has anyone any idea how to solve this?</p>
<p>I don't have GIGA R1, so no practical way to test this. I also cannot explain why it's showing up as square for you. It is common behaviour for character codes that don't have a font glyph to render in that way, but the one in question (null character) does not do that for me under the 1.x 2.x IDEs.</p> <p>However, the rest of what follows may help.</p> <p><a href="https://github.com/arduino-libraries/USBHostGiga/blob//bb48eb/USBHostGiga.h#L135" rel="nofollow noreferrer">According to github</a>, the type that is returned by <code>.read()</code> is <code>HID_KEYBD_Info_TypeDef</code>, so if you want you should be able to:</p> <pre class="lang-cpp prettyprint-override"><code>const HID_KEYBD_Info_TypeDef _key = keyb.read(); </code></pre> <p>However, there's not much wrong with using <code>auto</code> here. So far as I can tell, what you're <a href="https://github.com/arduino-libraries/USBHostGiga/blob/bb48eb72297b56063c48d465b392252224a99d67/usbh_hid_keybd.h#L283" rel="nofollow noreferrer">really receiving</a> is the content of <a href="https://wiki.osdev.org/USB_Human_Interface_Devices#Report_format" rel="nofollow noreferrer">Boot mode HID reports</a>. Not <em>individual</em> key information really, but rather the state which may include up to 6 pressed keys. If you're only pressing one key (one <em>non-shift state key</em>; as in not &quot;shift&quot;, &quot;control&quot;, &quot;alt&quot;. etc, it shows up in array index 0, which is what <a href="https://github.com/arduino-libraries/USBHostGiga/blob/bb48eb72297b56063c48d465b392252224a99d67/USBHostGiga.cpp#L29" rel="nofollow noreferrer">getAscii</a> is <a href="https://github.com/arduino-libraries/USBHostGiga/blob/bb48eb72297b56063c48d465b392252224a99d67/usbh_hid_keybd.c#L426" rel="nofollow noreferrer">ultimately interpreting</a>.</p> <p>So when you release the key (all of them) you are getting a report with nothing (no key code; represented with a zero value) in <code>keys[0]</code>, and so there's nothing there from which to get an ASCII code. What it seems to be doing is translating the 0 value that's there into <a href="https://github.com/arduino-libraries/USBHostGiga/blob/bb48eb72297b56063c48d465b392252224a99d67/usbh_hid_keybd.c#L291" rel="nofollow noreferrer">another zero</a>.</p> <p>So, it would seem all you need to do is check to see if it's a zero after the call to <code>getAscii</code>, e.g.:</p> <pre class="lang-cpp prettyprint-override"><code>if (keyb.available()) { const auto keyboard_input_report /*not really a key*/ = keyb.read(); const auto first_as_ascii = keyb.getAscii(keyboard_input_report); // where getAscii really means getAsciiCodeOfFirstkeyIfThereIsOneInTheReport if (first_as_ascii != 0) { Serial.println(first_as_ascii); } } </code></pre> <p>You could to check before translation with <code>if (keyboard_input_report.keys[0] != 0) {</code>. However, the former may make more sense. Because not every key on the keyboard will map unto may onto an ASCII code value anyway. E.g. ASCII does not represent the arrow keys, function keys, or page-up/page-down.</p> <p>In any case, this code may have issues if multiple keys are pressed. It looks like doing so correctly would involve <a href="https://github.com/arduino-libraries/USBHostGiga/blob/bb48eb72297b56063c48d465b392252224a99d67/usbh_hid_keybd.c#L422-L426" rel="nofollow noreferrer">using the internals</a> of <code>getAscii</code> to consult the translation tables for all six of the entries in the report's <code>keys</code> array.</p>
94731
|c++|piezo|
How do you use two piezos at the same time?
2023-11-04T13:13:01.093
<p>I'm trying to replicate a short music clip with two piezos, and I want them to play at the same time. While the right piezo is playing, I want the left one to still be looping. The problem is, I'm not sure how.</p> <p><a href="https://i.stack.imgur.com/awuWd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/awuWd.png" alt="enter image description here" /></a></p> <pre><code>//Left hand const int leftPin = 10; /Left pin const int leftTones[] = {123.4, 103.83, 138.59, 92.50}; //The looping left tones const int leftDelays[] = {700, 1300, 900, 900}; //How long those tones last const int leftNotes = 4; //How many left notes there are //Right hand const int rightPin = 2; //Right pin const int rightTones[] = {739.99, 587.33, 587.33, 659.25, 698.46, //The looping right tones 659.25, 587.33, 554.37, 587.33, 659.25, 739.99, 987.77, 493.88, 554.37, 587.33, 659.25, 587.33, 554.37, 880.00, 783.99, 739.99, 587.33, 587.33, 659.25, 698.46, 659.25, 587.33, 554.37, 587.33, 659.25, 739.99, 987.77, 987.77, 1108.73, 1174.66, 783.99, 739.99, 698.46, 1174.66, 1318.51}; const int rightDelays[] = {700, 1000, 100, 100, 300, 300, 200, //How long those tones last 300, 300, 200, 700, 700, 250, 150, 200, 400, 300, 300, 400, 200, 700, 1000, 100, 100, 300, 300, 200, 400, 300, 200, 700, 700, 300, 200, 400, 300, 200, 400, 300, 200}; const int rightNotes = 40; //How many right notes there are void setup(){ pinMode(leftPin, OUTPUT); pinMode(rightPin, OUTPUT); delay(1000); } void loop(){ for (int i = 0; i &lt; leftNotes; i++){ tone(leftPin, leftTones[i]); delay(leftDelays[i]); noTone(leftPin); } for (int i = 0; i &lt; rightNotes; i++){ tone(rightPin, rightTones[i]); delay(rightDelays[i]); noTone(rightPin); } } </code></pre> <p>With this code, the left piezo plays first, and then the right piezo plays. It should be at the same time.</p> <p>Edited Code:</p> <pre><code>long currentMillis = 0; long leftPreviousMillis = 0; // previous time for left hand long rightPreviousMillis = 0; // previous time for right hand const int leftNotes = 4; // The amount of left notes const int rightNotes = 40; // The amount of right notes int leftIndex = 0; // The specific index for the left piezo int rightIndex = 0; // The specific index for the right piezo const int leftPin = 10; // The left piezo const int rightPin = 2; // The right piezo // The specific left pitches (as float) const float leftTones[] = {123.4, 103.83, 138.59, 92.50}; // How long the left pitches last for const long leftDelays[] = {700, 1300, 900, 900}; // The specific right pitches (as float) const float rightTones[] = {739.99, 587.33, 587.33, 659.25, 698.46, 659.25, 587.33, 554.37, 587.33, 659.25, 739.99, 987.77, 493.88, 554.37, 587.33, 659.25, 587.33, 554.37, 880.00, 783.99, 739.99, 587.33, 587.33, 659.25, 698.46, 659.25, 587.33, 554.37, 587.33, 659.25, 739.99, 987.77, 987.77, 1108.73, 1174.66, 783.99, 739.99, 698.46, 1174.66, 1318.51}; // How long the right pitches last for const long rightDelays[] = {700, 1000, 100, 100, 300, 300, 200, 300, 300, 200, 700, 700, 250, 150, 200, 400, 300, 300, 400, 200, 700, 1000, 100, 100, 300, 300, 200, 400, 300, 200, 700, 700, 300, 200, 400, 300, 200, 400, 300, 200}; void setup() { pinMode(leftPin, OUTPUT); pinMode(rightPin, OUTPUT); Serial.begin(9600); delay(1000); tone(rightPin, rightTones[rightIndex]); tone(leftPin, leftTones[leftIndex]); } void loop() { currentMillis = millis(); // Left hand notes if (currentMillis - leftPreviousMillis &gt;= leftDelays[leftIndex]) { noTone(leftPin); // Turn off the left note leftPreviousMillis = currentMillis; leftIndex++; if (leftIndex == leftNotes) // Reset left hand index leftIndex = 0; tone(leftPin, leftTones[leftIndex]); // Turn on the new left note } // Right hand notes if (currentMillis - rightPreviousMillis &gt;= rightDelays[rightIndex]) { noTone(rightPin); // Turn off the right note rightPreviousMillis = currentMillis; rightIndex++; if (rightIndex == rightNotes) // Reset right hand index rightIndex = 0; tone(rightPin, rightTones[rightIndex]); // Turn on the new right note } } </code></pre> <p>I've done some testing, and I think it's a problem with the tones function. Right now, this code only plays the right hand notes. The problem is this part:</p> <pre><code>tone(rightPin, rightTones[rightIndex]); tone(leftPin, leftTones[leftIndex]); </code></pre> <p>When I do this:</p> <pre><code>tone(leftPin, leftTones[leftIndex]); tone(rightPin, rightTones[rightIndex]); </code></pre> <p>Only the left hand notes are heard. But, it's not perfect. There's little beeps and buzzes every now and then. This leaves me with the conclusion that if there are two tones at the same time, it only plays the one it reads first. I've tested it with simpler code, and it stands true.</p> <p>So that begs the question, is it even possible to use two piezos at the same time with one Arduino? I'm testing it with the Arduino simulator tinkercad, so maybe that's the problem? My code works for the left piezo, and the right piezo. But when you put them together, everything messes up.</p>
<p>It's always good to look at the documentation when you have a question about how a piece of code works. In this case I looked at the page for the tone function which can be found here. <a href="https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/" rel="nofollow noreferrer">https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/</a></p> <p>And the second sentence on that page says it all:</p> <blockquote> <p>Only one tone can be generated at a time. If a tone is already playing on a different pin, the call to tone() will have no effect. If the tone is playing on the same pin, the call will set its frequency.</p> </blockquote>
94743
|programming|library|c-preprocessor|
is #ifdef __SD_H__ considered a bad practice?
2023-11-05T20:04:18.227
<p>Say I'm working on a library<sup>^<strong>1</strong></sup> to which I want to add support for <code>SD.h</code><sup>^<strong>2</strong></sup> but knowing for a fact that many microcotrollers don't support <code>SD.h</code> <em>(therefore they result in compilation errors [eg. Attiny85])</em> I don't want to just <code>#include &lt;SD.h&gt;</code> <em>(or even <code>#ifndef __SD_H__</code> then <code>#include &lt;SD.h&gt;</code>)</em> in <code>Mylibrary.h</code> and make it totally unusable for some microcontrollers. So I was wondering, is it considered ok to just add the functionality like...</p> <pre class="lang-cpp prettyprint-override"><code>// Mylibrary.h #ifdef __SD_H__ // Save functionality for those including `SD.h` to their `sketch.ino` void Mylibrary::save(String filename){ SD.open(filename, FILE_WRITE) // ... } #endif </code></pre> <p>...without ever including the <code>SD.h</code> in <code>Mylibrary.h</code> and hence force the user whenever he\she wants to use some SD functionallity, to just include <code>SD.h</code> in his\her <code>sketch.ino</code>? <strong>+</strong><em>(it sound exhausting to do something like <a href="https://github.com/GiorgosXou/NeuralNetworks/blob/31bb95e4cefcaefb28f6b031a634ded6c7274a7d/src/NeuralNetwork.h#L52-L55" rel="nofollow noreferrer">this</a> for every MCU, as an alternative way)</em></p> <p><sup>[<strong>1</strong>] <em>(in my case <a href="https://github.com/GiorgosXou/NeuralNetworks" rel="nofollow noreferrer">this library</a>)</em><br>[<strong>2</strong>] <em>(in my case something related to <a href="https://github.com/GiorgosXou/NeuralNetworks/issues/18#issuecomment-1792298022" rel="nofollow noreferrer">this</a>)</em><br><br><strong>PS.</strong> The reason I'm asking is because I don't remember seeing it anywhere being used that way and I'm slightly confused as to if this is the right or wrong thing to do so</sup></p>
<p>Yes, it is in general a bad practice to use include guard define to detect if the header file is included. It will work only in a header file in a compilation unit which includes the detected header file.</p> <p>In Arduino all ino files of the sketch are one compilation unit. But every C or C++ file is a separate compilations unit. They would not 'see' the include guard from an include in the ino file(s).</p> <p>If you want to use the include guard define, don't relay on it exclusively. Use your own define and set it if you detect the include guard. This way user can set it if theirs SD library has a different name for the include guard.</p> <pre><code>#ifdef __SD_H__ #define XY_USE_SD_LIB #endif #ifdef XY_USE_SD_LIB // Save functionality for those including `SD.h` to their `sketch.ino` void Mylibrary::save(String filename){ SD.open(filename, FILE_WRITE) // ... } #endif </code></pre> <p>I use this in my popular ArduinoOTA library <a href="https://github.com/JAndrassy/ArduinoOTA/blob/5f838871e213474e7dabf70f2ddfc5ecb6cb971a/src/ArduinoOTA.h#L121" rel="noreferrer">here</a>.</p> <p>There is other way to detect includes and it works across compilation units, but it doesn't work on all Arduino platforms. It is the <code>__has_include</code> 'directive'. I use it <a href="https://github.com/JAndrassy/TelnetStream/blob/6005d8d917ee64a80417bae5b4b964cf7a6b3726/src/NetTypes.h#L42" rel="noreferrer">here</a>.</p>
94750
|led|pins|
Just one more pin!
2023-11-06T16:31:36.197
<p>I have an Arduino project to control a motor's speed at 3 levels, indicated by 3 LEDs, so level 1 is speed 1 and LED 1, and so on for levels 2/3.</p> <p>Also, I added a low-battery voltage indicator to monitor the battery level.</p> <p>I am going to use an ATtiny45, which has 8 pins(Vcc, GND, 1 analog pin, 5 digital pins). The project needs 6 digital pins and 1 analog pin, so only one more pin is needed.</p> <p>I do not want to use an expander or I2C, as they will make the project more complex, and it is only one pin!</p> <p>I can use a larger microcontroller but it would be the last choice.</p> <p>Here is my project's diagram and code:</p> <p><a href="https://i.stack.imgur.com/tb4KJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tb4KJ.png" alt="enter image description here" /></a></p> <pre><code>//********************************************^************************************************ // https://forum.arduino.cc/t/control-motor-speed-with-npn-and-push-button-no-driver/1184925 // // // // Version YY/MM/DD Comments // ======= ======== ==================================================================== // 1.00 20/23/02 Running code // 1.10 20/23/03 Added motor and LEDs OFF if switch pressed for &gt;= 3 sec. // // // #define PRESSED HIGH #define RELEASED LOW #define ENABLED true #define DISABLED false #define LEDon HIGH #define LEDoff LOW #define MOTORoff 0 #define lipo A0 float lipoV = 0; //GPIOs const byte Button = 2; const byte ledpin = 3; const byte ledpin1 = 4; const byte ledpin2 = 5; const byte Motor = 9; const byte heartbeatLED = 13; const byte Red = 6; //Variables byte lastButton = RELEASED; byte currSwitch; int Speed_Level; bool bCheckingSwitch = DISABLED; //timing stuff unsigned long heartbeatTime; unsigned long switchesTime; unsigned long threeSecondTime; // s e t u p ( ) //********************************************^************************************************ void setup() { pinMode(Button, INPUT); pinMode(lipo, INPUT); pinMode(ledpin, OUTPUT); pinMode(ledpin1, OUTPUT); pinMode(ledpin2, OUTPUT); pinMode(Motor, OUTPUT); pinMode(heartbeatLED, OUTPUT); pinMode(Red, OUTPUT); } //END of setup() // l o o p ( ) //********************************************^************************************************ void loop() { //************************************************ T I M E R heartbeatLED //is it time to toggle the heartbeat LED ? if (millis() - heartbeatTime &gt;= 500ul) { //restart this TIMER heartbeatTime = millis(); //toggle the heartbeat LED if (digitalRead(heartbeatLED) == HIGH) digitalWrite(heartbeatLED, LOW); else digitalWrite(heartbeatLED, HIGH); } //************************************************ T I M E R check switches //is it time to check our switches ? if (millis() - switchesTime &gt;= 50ul) { //restart this TIMER switchesTime = millis(); checkSwitches(); } //************************************************ T I M E R three seconds //if enabled, is it time to turn things OFF ? if (bCheckingSwitch == ENABLED &amp;&amp; millis() - threeSecondTime &gt;= 2000ul) { //we are finished with this TIMER bCheckingSwitch = DISABLED; //restart the sequence Speed_Level = -1; analogWrite(Motor, MOTORoff); digitalWrite(ledpin, LEDoff); digitalWrite(ledpin1, LEDoff); digitalWrite(ledpin2, LEDoff); digitalWrite(Red, LEDoff); } } //END of loop() // c h e c k S w i t c h e s ( ) //********************************************^************************************************ void checkSwitches() { byte state; //************************************************ Button state = digitalRead(Button); //has there been a state change in the switch ? if (lastButton != state) { //update to the new state lastButton = state; //******************************* if (state == PRESSED) { //enable the TIMER bCheckingSwitch = ENABLED; //start the TIMER threeSecondTime = millis(); } //******************* //the switch was released else { //disable the TIMER bCheckingSwitch = DISABLED; Speed_Level++; lipoV = analogRead(lipo); //battery checker if(lipoV &lt; 680){ digitalWrite(Red,LEDon); } else { digitalWrite(Red,LEDoff); } //don't go over 3 if (Speed_Level &gt;= 4) { Speed_Level = 0; } //******************* if (Speed_Level == 1) { analogWrite(Motor, 50); digitalWrite(ledpin, LEDon); digitalWrite(ledpin1, LEDoff); digitalWrite(ledpin2, LEDoff); } //******************* else if (Speed_Level == 2) { analogWrite(Motor, 75); digitalWrite(ledpin, LEDoff); digitalWrite(ledpin1, LEDon); digitalWrite(ledpin2, LEDoff); } //******************* else if (Speed_Level == 3) { analogWrite(Motor, 100); digitalWrite(ledpin, LEDoff); digitalWrite(ledpin1, LEDoff); digitalWrite(ledpin2, LEDon); } //******************* else { analogWrite(Motor, MOTORoff); digitalWrite(ledpin, LEDoff); digitalWrite(ledpin1, LEDoff); digitalWrite(ledpin2, LEDoff); digitalWrite(Red,LEDoff); } } } }//END of checkSwitches() //********************************************^************************************************ </code></pre> <p>Can I use tA0 as input and output at the same time like this?</p> <p><a href="https://i.stack.imgur.com/KnlLG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KnlLG.png" alt="enter image description here" /></a></p> <p>Or can I reduce the LED pins, meaning use 1 pins for 2 LEDs?</p>
<p>As a (slightly hacky and binary :) ) suggestion, you could use just two LEDs and free up a pin with the following...</p> <p>Level 1 - LED 1 on, LED 2 off</p> <p>Level 2 - LED 1 off, LED 2 on</p> <p>Level 3 - LED 1 on, LED 2 on</p> <p>This is a really simple change to your current set up and code</p> <p>Alternatively (as suggested by @dandavis) use a set of 3 neopixels and drive from just 1 pin</p>
94752
|c++|
Using Adafruit RTClib without fragmenting the heap
2023-11-07T00:08:07.173
<p>I'm getting ready to add DS1307 support to my Arduino app, and was <em>horrified</em> when I looked at the sourcecode for the RTC_DS1307 class in Adafruit's RTClib library...</p> <pre><code>DateTime RTC_DS1307::now() { uint8_t buffer[7]; buffer[0] = 0; i2c_dev-&gt;write_then_read(buffer, 1, buffer, 7); return DateTime(bcd2bin(buffer[6]) + 2000U, bcd2bin(buffer[5]), bcd2bin(buffer[4]), bcd2bin(buffer[2]), bcd2bin(buffer[1]), bcd2bin(buffer[0] &amp; 0x7F)); } </code></pre> <p>... and realized that it appears to be instantiating a new throw-away DateTime object on the heap every time you call now()... which AFAIK, is the <strong>ultimate</strong> Arduino C++ taboo.</p> <p>I was about to tear into the class and rewrite it to reuse a singleton DateTime object that gets created once and reused forever... but then I remembered about return value optimization.</p> <p><strong>Is</strong> this actually a scenario where RVO will automagically kick in to save the day and prevent a heap-allocation (by pre-allocating space for the DateTime object on the caller's stack prior to calling <code>now()</code>), or is this library indeed doing something as taboo as I think it is?</p>
<p>I wrote a minimal sketch that calls <code>RTC_DS1307::now()</code>, disassembled it, and here is what I saw:</p> <ul> <li><p>The caller allocates 6 bytes on the stack for holding the return value.</p> </li> <li><p>It writes the address of this stack location in the register pair r25:r24, as per the AVR calling convention,<sup>1</sup> then calls <code>RTC_DS1307::now()</code>.</p> </li> <li><p>As the callee computes the fields of the resulting <code>DateTime</code> (by means of inlined calls to <code>bcd2bin()</code>), it writes them directly into the caller's stack frame, with no intermediate copy in RAM.</p> </li> </ul> <p>This looks to me like return value optimization.</p> <p><strong>However</strong>, in order to witness this behavior, I had to call <code>RTC_DS1307::now()</code> <em>twice</em>. If the method is called from a single place within the sketch, the compiler inlines it, and there isn't even a function call to begin with.</p> <p>Then, of course, the heap is never touched.</p> <p><sup>1</sup> <i>You would expect the <code>this</code> pointer to be passed as the first argument, in r25:r24. It would seem it has been optimized out, which makes sense given that there is only one <code>RTC_DS1307</code> object in the whole sketch.</i></p>
94775
|arduino-uno|
Why my pushbutton always reads LOW?
2023-11-09T17:19:34.310
<p>This is the code I used in my project</p> <pre><code>void setup() { Serial.begin(9600); pinMode(6,OUTPUT); pinMode(7,OUTPUT); pinMode(8,OUTPUT); pinMode(9,OUTPUT); pinMode(10,OUTPUT); pinMode(11,OUTPUT); pinMode(12,OUTPUT); pinMode(5,INPUT); } void loop() { Serial.println(digitalRead(5)); if(digitalRead(5)==HIGH){ blink(12,100); blink(11,100); blink(10,100); blink(9,100); blink(8,100); blink(7,100); blink(6,100); Serial.println(&quot;blink done&quot;); } } void blink(int a,int b) { digitalWrite(a,HIGH); delay(b); digitalWrite(a,LOW); delay(b); } </code></pre> <p><a href="https://i.stack.imgur.com/0crVI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0crVI.png" alt="Image of Tinkercad of my work" /></a></p> <blockquote> <p>Project link <a href="https://www.tinkercad.com/things/55vY18FFxDR-blinking-led-wave/editel?sharecode=xQAM80Uu6sJ-hBnLLd04KasomJ2eNNzWLgKZMARe4ig" rel="nofollow noreferrer">https://www.tinkercad.com/things/55vY18FFxDR-blinking-led-wave/editel?sharecode=xQAM80Uu6sJ-hBnLLd04KasomJ2eNNzWLgKZMARe4ig</a></p> </blockquote>
<p>When you press the button, you short the bottom blue (GND) and the bottom red (+5V) lines. That will in the least serious case cause your Arduino to reset, but could also damage the button, burn a wire or a capacitor, or brick your Arduino. There's some protection on the board to prevent serious damage or even injury to someone, but still you should <strong>absolutely avoid</strong> shorting +5V to GND.</p> <p>The fix is actually quite simple: Replace the short blue wire with a large resistor, something like 10k. Then the Button will still read low when it's not pressed, but read high when it's pressed. That's called a &quot;pull-down&quot; resistor.</p>
94781
|usb|arduino-due|uart|
Best Solution to Parallel UART reads with Arduino Due
2023-11-10T15:20:53.390
<p>I have 4 Arduino boards pushing data over UART to 4 serial ports on the Arduino Due at <code>115200</code> baud rate.</p> <p>Data format - <code>&lt;Short URL&gt;,&lt;Number of the Node&gt;</code></p> <p>Eg: <code>px.ht/d/mCxG,1&quot;</code></p> <p>Arduino Due has 4 hardware serial ports and one native USB port. I want to interface all the 4 UART nodes to each hardware serial of the Due and then push this data onto the <code>SerialUSB</code> port which is native USB at baud rate of <code>2000000</code>.</p> <p><strong>What did I try?</strong></p> <ol> <li>Sequential read of all Serial ports - Obviously poor performance</li> <li>Used Serial Events - For some reason never able to get the callback triggered.</li> <li>Used some FreeRTOS library and there are a lot of data misses.</li> </ol> <p>When using RTOS, the data from multiple nodes is getting mixed up and printed incorrectly. I'm looking for some efficient way to read parallel data from all UARTs without data overlap and stream data and given the MCU on Arduino Due is very powerful I don't think that's what is bottlenecking the performance.</p>
<blockquote> <p>It seems the arduino's wrappers for serial API's are very slow</p> </blockquote> <p>They aren't. There are some functions that depend on timeouts: these can indeed be very slow. However, if you read the ports in a <em>non blocking</em> fashion, everything should be fast. Non blocking basically means never waiting, and never trying to read more bytes than what is currently <code>available()</code>. For example:</p> <pre class="lang-cpp prettyprint-override"><code>const int buffer_size = 64; // tune to taste char buffer1[buffer_size]; int size1 = 0; // same for buffer2, size2, etc. void loop() { while (Serial1.available()) { char c = Serial1.read(); if (size1 &lt; buffer_size - 1) buffer1[size1++] = c; // buffer the incoming character if (c == '\n') { // found end-of-message buffer1[size1] = '\0'; // terminate the string Serial.print(buffer1); // send through USB size1 = 0; // get ready for next message } } // then the same for Serial2, ... } </code></pre> <p>If you know a bit about object oriented programming, you can easily rewrite this in a more elegant way, with no repeated code.</p>
94784
|programming|led|attiny85|
Make two LEDs fade in and out with with different PWM values
2023-11-11T00:23:47.440
<p>I have two UV leds, one Vf 3.3V @ 150 mA and the second one Vf 5V @ 150 mA. I need a circuit to make them fade in and out alternatively, <em>i.e.</em>, as one goes dimmer the other goes brighter and vice versa. I tried an Arduino PWM transistor approach with the Attiny85 board and the code below and it works, but I need the <em>ledPin2</em> led to work with at a lower <em>maxbrightness</em>. How can I modify the code so that I can set the <em>maxbrightness</em> for <em>ledPin2</em> to be around 25, while the <em>maxbrightness</em> for <em>ledPin1</em> remains 255 and yet both take the same time to fade in and out?</p> <pre><code>int ledPin1 = 0; int ledPin2 = 4; int minbrightness = 0; int maxbrightness = 255; int fadeAmount = 1; int tim=4; void setup() { pinMode(ledPin1, OUTPUT); pinMode(ledPin2, OUTPUT); } void loop() { analogWrite(ledPin1, minbrightness); analogWrite(ledPin2, maxbrightness); minbrightness = minbrightness + fadeAmount; maxbrightness = maxbrightness - fadeAmount; if (minbrightness == 0 || minbrightness == 255 ){ fadeAmount = -fadeAmount ; } delay(tim); } </code></pre>
<p>I don't think you have much choice than to come up with a sort of a counter and instead of having a single variable for the brightness of all the LEDs, you'll have to maintain a separate brightness variable for each channel which will have its own unique dimming profile. You'll then have to empirically determine how many counts it'll take for you to decrease/increase the PWM duty cycle on each separate channel (since perceived brightness isn't linear).</p> <p>Something like this? The brightness of 32 and a modulo 8 was chosen to be a factor of 256, so it's more or less synced.</p> <pre><code>int ledPin1 = 0; int ledPin2 = 4; int brightnessLP1 = 0; //begin with the LED off int brightnessLP2 = 32; //begin with the LED on int fadeAmount = 1; int tim=4; void setup() { pinMode(ledPin1, OUTPUT); pinMode(ledPin2, OUTPUT); } void loop() { //counter value accommodates the modulo below for(int brightnessCounter = 1; brightnessCounter &lt; 257; brightnessCounter++) { analogWrite(ledPin1, brightnessLP1); analogWrite(ledPin2, brightnessLP2); brightnessLP1 = brightnessLP1 + fadeAmount; if(brightnessCounter % 8) { brightnessLP2 = brightnessLP2 - fadeAmount; } delay(tim); } fadeAmount = -fadeAmount; } </code></pre> <p>I'm sure you could make it cleaner or link the brightness values to the counter, but I'll leave that to you.</p>
94798
|pins|feather|
Why isn't pin 6 on my Adafruit Feather RP2040 being sent high when I ask it to?
2023-11-12T20:46:14.393
<p>I have an Adafruit Feather RP2040 (<a href="https://learn.adafruit.com/adafruit-feather-rp2040-pico/pinouts" rel="nofollow noreferrer">pinouts</a>) connected via pin 6 to a <a href="https://www.adafruit.com/product/2895" rel="nofollow noreferrer">relay</a>. The code (below) triggers the relay when a separate color sensor returns &quot;enough&quot; red values.</p> <p>The color sensor works (confirmed by the serial print statements); the on-board LED (connected internally to pin 13) lights up when it should; but I don't get any voltage on pin 6 when I should. I'm testing the voltage with a standard multimeter. If I move my connecting wire from pin 6 to pin 13, I get voltage (and the relay activates). Why doesn't pin 6 get voltage? What else can I do to diagnose the issue?</p> <p>Software versions:</p> <ul> <li>Arduino.CC IDE v2.2.1 (latest)</li> <li>Arduino IDE Board manager: added <a href="https://github.com/earlephilhower/arduino-pico" rel="nofollow noreferrer">https://github.com/earlephilhower/arduino-pico</a>, version 3.6.0 (latest)</li> <li>Adafruit APDS9960 Library from <a href="https://github.com/adafruit/Adafruit_APDS9960" rel="nofollow noreferrer">https://github.com/adafruit/Adafruit_APDS9960</a>, version 1.2.3, released Jan 30 of this year. According to <a href="https://github.com/adafruit/Adafruit_APDS9960/tags" rel="nofollow noreferrer">https://github.com/adafruit/Adafruit_APDS9960/tags</a> there is a version 1.2.4 released on May 12th, but since this is just the light sensor code, which is behaving correctly, I don't believe the issue lies here.</li> </ul> <p>Code:</p> <pre class="lang-cpp prettyprint-override"><code>// copied &amp; modified from the source at: // https://github.com/adafruit/Adafruit_APDS9960/blob/master/examples/color_sensor/color_sensor.ino #include &quot;Adafruit_APDS9960.h&quot; Adafruit_APDS9960 apds; // the pin on the feather that we're using to talk to the relay #define PIN_TO_RELAY 6 #define BUCKET_FULL_RED 50 void setup() { // enable Serial communication Serial.begin(115200); // try to start the color sensor if(!apds.begin()) { Serial.println(&quot;failed to initialize device! Please check your wiring.&quot;); } else { // Assume success // Serial.println(&quot;Device initialized!&quot;); // we want color readings apds.enableColor(true); } // define the relay pin as an OUTPUT pin pinMode(PIN_TO_RELAY, OUTPUT); // start with the relay &quot;open&quot; AKA not running the pump digitalWrite(PIN_TO_RELAY, LOW); // use the built-in LED as an external signal for &quot;pumping&quot; pinMode(LED_BUILTIN, OUTPUT); } void loop() { // create some variables to store the color data in; unused, except for 'red' uint16_t red, green, blue, clear; // for checking the relay pin state int relay_pin_state = 0; // for extra printing int debug = 1; // wait for color data to be ready while (!apds.colorDataReady()) { delay(5); } // get fresh data; we only care about the red, but we have to read them all apds.getColorData(&amp;red, &amp;green, &amp;blue, &amp;clear); if (debug) { Serial.print(&quot;current red value is:&quot;); Serial.println(red); } if (debug &gt; 2) { relay_pin_state = digitalRead(PIN_TO_RELAY); if (relay_pin_state == HIGH) { Serial.println(&quot;steadystate: Relay pin is HIGH / enabled&quot;); } else { Serial.println(&quot;steadystate: Relay pin is LOW / disabled&quot;); } } if (red &gt; BUCKET_FULL_RED) { if (debug) { Serial.println(&quot;start the pump (for 5 sec)&quot;); } // light up the built-in LED digitalWrite(LED_BUILTIN, HIGH); // &quot;close&quot; the relay to turn on the pump digitalWrite(PIN_TO_RELAY, HIGH); if (debug &gt; 2) { relay_pin_state = digitalRead(PIN_TO_RELAY); if (relay_pin_state == HIGH) { Serial.println(&quot;pumping: Relay pin is HIGH / enabled&quot;); } else { Serial.println(&quot;pumping: Relay pin is LOW / disabled&quot;); } } // wait for a while for the pump to do its work // 5 sec in ms; TODO: eventually circa 4 min delay(5 * 1000); if (debug) { Serial.println(&quot;stop the pump&quot;); } // turn off the built-in LED digitalWrite(LED_BUILTIN, LOW); // &quot;open&quot; the relay to turn off the pump digitalWrite(PIN_TO_RELAY, LOW); } // no need to cycle quickly; wait 1 sec in ms delay(1 * 1000); } </code></pre> <p>I just looked more closely at the pinouts page again, and was surprised to see the hole labeled &quot;6&quot; on the front is labeled &quot;GP08&quot; on the back, which corresponds to &quot;GPIO8&quot; in <a href="https://learn.adafruit.com/assets/107203" rel="nofollow noreferrer">https://learn.adafruit.com/assets/107203</a>. I wonder if I'm sending the &quot;D4&quot; pin HIGH (&quot;GPIO6&quot;) instead of the one I'm expecting.</p>
<p>Turns out I misled you with my ignorance. I took for granted that the thing labeled &quot;6&quot; on the front was in fact Pin 6, but it's not:</p> <p><a href="https://i.stack.imgur.com/hLxZ2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hLxZ2.jpg" alt="feather with pin &quot;6&quot; circled" /></a></p> <p>Indeed, if I turn it over, that's &quot;GP08&quot;:</p> <p><a href="https://i.stack.imgur.com/zi9kS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zi9kS.jpg" alt="reverse face of feather with the same location labeled &quot;GP08&quot;" /></a></p> <p>... and so my code needs to use pin 8, not pin 6.</p> <p>User <a href="https://arduino.stackexchange.com/users/70020/timemage">timemage</a> pointed out similar confusion on a recent post: <a href="https://arduino.stackexchange.com/questions/94659/d1-mini-esp8266-no-sound-on-speaker">D1 mini ESP8266 no sound on speaker</a> where the silk-screened label on the front of the board did not match the actual pin number. They additionally point out a file that I would have never stumbled upon, but demonstrates this mapping: <a href="https://github.com/adafruit/circuitpython/blob/16c8c9a739cfe0db2c712696eb340de2d7944d41/ports/raspberrypi/boards/adafruit_feather_rp2040/pins.c#L24" rel="nofollow noreferrer">https://github.com/adafruit/circuitpython/blob/16c8c9a739cfe0db2c712696eb340de2d7944d41/ports/raspberrypi/boards/adafruit_feather_rp2040/pins.c#L24</a>, namely:</p> <pre><code> { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&amp;pin_GPIO2) }, { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&amp;pin_GPIO3) }, { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&amp;pin_GPIO7) }, { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&amp;pin_GPIO8) }, /* right here */ { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&amp;pin_GPIO9) }, { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&amp;pin_GPIO10) }, </code></pre> <p>The description of <a href="https://learn.adafruit.com/adafruit-feather-rp2040-pico/pinouts" rel="nofollow noreferrer">the pinout</a> still contains some misleading information, in my opinion:</p> <blockquote> <p>D6/GP08 - Digital I/O pin 6. It is also SPI1 MISO, UART1 TX, I2C0 SDA and PWM4 A.</p> </blockquote> <p>Here, it seems to me that this spot is still being called &quot;pin 6&quot;.</p>
94806
|compile|arduino-cli|
How to find out all #define used by arduino-cli in compile?
2023-11-13T19:34:53.207
<p>How to find out all <code>#define</code> used by <code>arduino-cli</code> in compile?</p> <p>I had seen something some time ago, but I cannot find it again. I think that it was some option somewhere, and the result was that the compile did not end normally, but some generated file contained lots of useful and lots of obscure defined names.</p> <p>I would like to find everything that's defined in my program, which I want to write, compile, and then run on different Arduinos, but it sometimes need different Serial to be used, different pin assignments, different internal buffer sizes and so on.</p> <p>And I would like to organize the differences better, than just put all and everything to one big <code>#ifdef</code> - <code>#endif</code> for each extra platform.</p> <p>Something like:</p> <ul> <li>if it does not have <code>Serial</code> but <code>Serial1</code>, <code>#define Serial Serial1</code></li> <li>if it has 2kB RAM or less, set MY_BUF_SIZE to 10; if it has less than 3kB use 30, else use 100.</li> <li>but if it is <code>Micro Pro</code>, use this pin assignment, else if it is <code>Nano Every</code> use that, else issue error/warning for user, that pins need to be assigned.</li> </ul> <p>And many others...</p>
<p>I am not familiar with arduino-cli. If you can manage to find the <code>g++</code> command line it uses for compiling your sketch, then you can get the list you are looking for by using a modified version of that command:</p> <ul> <li>add the options <code>-E -dM</code></li> <li>find the option <code>-o output_file</code> and change the name of the output file to something more appropriate.</li> </ul> <hr /> <p><strong>Edit</strong>: Following a suggestion by @gilhad, you can build the required command line by piping the output of arduino-cli through <code>sed</code>:</p> <pre class="lang-shell prettyprint-override"><code>arduino-cli compile | \ sed -n '/g++.*\.ino\.cpp\.o/{s/-MMD//;s/-o .*/-E -dM -o defines.dump/;p}' </code></pre>
94811
|serial|python|
Reading serial data from Arduino in Python continually
2023-11-14T01:32:40.003
<p>Using a stepper motor and a range finder (TFLuna), I am trying to build a &quot;Lidar&quot; (like a Radar, but with light). Here is the algorithm:</p> <ul> <li>Turn motor one step, calculate angle, measure distance to whatever it hits, giving polar coordinates;</li> <li>Calculate Cartesian coordinates and send to Python;</li> <li>Collect a few hundred measurements and show the scatter plot.</li> </ul> <p>This works, but only if I restart the sketch and the Python routine at the same time. After I collected all the data for one plot, I cannot restart the Python script to collect another round of data - it shows that there is no data in waiting. Also, the Arduino script never hangs due to the buffer getting full (as Python has stopped reading).</p> <p>How can I make it so that the Arduino and the motor do their thing (swinging back and forth 180º, looking at stuff), and I am able to collect an amount of data in Python intermittently -- whenever I choose to restart the script one more time?</p> <p>Here is the code. First, Arduino. &quot;count&quot; is the number of steps by which the motor has rotated; tflI2C is the range-finder object.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;Stepper.h&gt; #include &lt;Arduino.h&gt; #include &lt;Wire.h&gt; // Instantiate the Wire library #include &lt;TFLI2C.h&gt; // TFLuna-I2C Library v.0.1.1 #include &lt;math.h&gt; TFLI2C tflI2C; int16_t tfDist; // distance in centimeters int16_t tfAddr = TFL_DEF_ADR; // Use this default I2C address const int stepsPerRevolution = 2048; // change this to fit the number of steps per revolution // initialize the stepper library on pins 8 through 11: Stepper myStepper(stepsPerRevolution, 8, 10, 9, 11); int stepCount = 0; // number of steps the motor has taken void serialFlush(){ while(Serial.available() &gt; 0) { char t = Serial.read(); } } void setup() { // initialize the serial port: Serial.begin(115200); Wire.begin(); // Initalize Wire library myStepper.setSpeed(10); //myStepper.step(stepsPerRevolution/2); //delay(1000); //myStepper.step(-stepsPerRevolution/2); } void coordinates(int count){ struct Polar { float angle; int16_t distance; } pPoint; struct Cartesian { float xCoord; float yCoord; } cPoint; float angle = count*(2.0*PI)/stepsPerRevolution; byte flag = 0; //Serial.flush(); while (Serial.availableForWrite() &lt; sizeof(struct Cartesian)){} if(tflI2C.getData(tfDist, tfAddr)){ pPoint.angle = angle + PI/2.0; pPoint.distance = tfDist; cPoint.xCoord = pPoint.distance * cos(pPoint.angle); cPoint.yCoord = pPoint.distance * sin(pPoint.angle); if (pPoint.distance &lt;= 50 ){ Serial.write((char*)&amp;cPoint, sizeof(struct Cartesian)); } } return; } void loop() { // step one step: for (int k=0; k&lt;stepsPerRevolution/4; k++){ myStepper.step(1); coordinates(stepCount); stepCount += 1; delay(10); } for (int k=0; k&lt;stepsPerRevolution/2; k++){ myStepper.step(-1); coordinates(stepCount); stepCount -= 1; delay(10); } for (int k=0; k&lt;stepsPerRevolution/4; k++){ myStepper.step(1); coordinates(stepCount); stepCount += 1; delay(10); } delay(5000); } </code></pre> <p>and here is Python:</p> <pre class="lang-python prettyprint-override"><code>ardu = serial.Serial('/dev/cu.usbserial-1460', baudrate=115200, timeout=.1) radarImage = [] structSize = struct.calcsize(&quot;ff&quot;) ardu.reset_input_buffer() i = 0; while True: if ardu.in_waiting &gt;= structSize: arduRead = ardu.read(structSize) point = list(struct.unpack(&quot;ff&quot;,arduRead)) if i &lt;= 10: print(point) radarImage.append(point) i += 1 else: pass if i &gt; 2000: break ardu.close() </code></pre> <p>Here is a sample from a &quot;first round&quot; data collection. Yes, my desk is messy...</p> <p><a href="https://i.stack.imgur.com/yMTiD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yMTiD.png" alt="enter image description here" /></a></p>
<blockquote> <p>I am puzzled why the Arduino code isn't simply stopping at &quot;Serial.availableForWrite()&quot; when I stop reading data on the Python side -- it keeps on running.</p> </blockquote> <p>This depends on the Arduino board used - specifically on if it has native USB support. Boards without native USB support (like Uno or Nano) use a second chip, which receives UART (Serial) data from the main chip and interfaces that to USB. The main chip cannot know about the state of the USB chip, so it will send regardless of a program listening.</p> <p>Boards with native USB support somewhat depend on the OS/driver/program to collect the data from the USB endpoints. If your program doesn't collect that data, but also doesn't close the connection, then the data will pile up in the buffer and <code>availableForWrite()</code> should return 0 when the buffer is full (blocking further writing to Serial). But if your program closes the connection correctly (as it should on exiting), then the Serial data doesn't even get send, but discarded. See <a href="https://arduino.stackexchange.com/questions/72189/what-happens-to-serial-output-when-no-one-is-listening">Majenkos answer to this question</a>, which is relevant here.</p> <p>So generally: No, the Arduino won't stop sending data, only because you don't listen. Building a simple command system to tell the Arduino to start/stop sending data is a common way to handle this situation. Or you could implement a protocol, which lets the python script correctly detect start and end of each data packet.</p>
94823
|esp8266|json|watchdog|
Need help with parsing NWS JSON weather alerts causing reset on ESP8266
2023-11-15T02:37:07.220
<p>I'm trying to parse the JSON string from the National Weather Service Alerts and am encountering a problem where the code can't parse the value and the device auto-resets. I've used this code before on a different API to get the current weather conditions, and that works fine - I'm not sure what I'm doing wrong and would greatly appreciate any advice or help. Thanks!</p> <p>Here is the error:</p> <pre> 21:13:07.521 -> wdt reset 21:13:07.521 -> load 0x4010f000, len 3424, room 16 21:13:07.521 -> tail 0 21:13:07.521 -> chksum 0x2e 21:13:07.521 -> load 0x3fff20b8, len 40, room 8 21:13:07.521 -> tail 0 21:13:07.521 -> chksum 0x2b 21:13:07.521 -> csum 0x2b 21:13:07.521 -> v00045d00 21:13:07.521 -> ~ld 21:13:07.555 -> ����n�r��n|�l�l`b��|r�l�n��n�l`��r�l�l�� </pre> <p>And here's my code:</p> <pre><code>#include &lt;ESP8266WiFi.h&gt; #include &lt;ArduinoJson.h&gt; const char* ssid = &quot;mySSID&quot;; // SSID of local network const char* password = &quot;myPassword&quot;; // Password on network WiFiClient client; char weatherServerName[] = &quot;api.weather.gov&quot;; String result; //For testing change this zone to any zone from the NWS that's currently experiencing a weather alert //Find an active alert area by going to https://api.weather.gov/alerts/active and looking for the code in the &quot;affectedZones&quot; String zone = &quot;LEZ144&quot;; bool hasAlert = false; void setup() { Serial.begin(115200); Serial.println(&quot;=====================================================================================================&quot;); Serial.println(&quot;Connecting&quot;); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print(&quot;.&quot;); } Serial.println(&quot;Connected&quot;); delay(1000); } void loop() { Serial.println(&quot;:D&quot;); getWeatherAlerts(); delay(100000); } void getWeatherAlerts() { String server = weatherServerName; if (client.connect(server, 443)) { client.println(&quot;GET /alerts/active?zone=&quot; + zone); client.println(&quot;User-Agent: ArduinoWiFi/1.1&quot;); client.println(&quot;Connection: close&quot;); client.println(); } else { Serial.println(&quot;connection failed&quot;); //error message if no client connect Serial.println(); } //waits for data while (client.connected() || client.available()) { //connected or data available char c = client.read(); //gets byte from ethernet buffer result = result+c; } client.stop(); //stop client result.replace('[', ' '); result.replace(']', ' '); Serial.println(result); char jsonArray [result.length()+1]; result.toCharArray(jsonArray,sizeof(jsonArray)); jsonArray[result.length() + 1] = '\0'; StaticJsonDocument&lt;8196&gt; root; DeserializationError error = deserializeJson(root, jsonArray); if (error) { Serial.println(&quot;parseObject() failed&quot;); } String features = root[&quot;features&quot;]; Serial.println(features); if(features.length() == 0) { Serial.println(features); hasAlert = false; } else { String severity = root[&quot;features&quot;][&quot;severity&quot;]; Serial.println(severity); if(severity == &quot;Moderate&quot; || severity == &quot;Severe&quot;) { hasAlert = true; } else { hasAlert = false; } } Serial.println(hasAlert); } </code></pre>
<p>There is a good clue in the first line of your reported error:</p> <pre><code>21:13:07.521 -&gt; wdt reset </code></pre> <p>The ESP-8266 Watchdog Timer (WDT) will reset the device if it has not been correctly 'fed' for a period of time (the watchdog timeout).</p> <p>As @Juraj noted, the ESP-8266 Arduino libraries 'helpfully' add WDT feeds at various points, suggesting the timeout is because your code is either crashing (overflowing into invalid program code) or is timing out (valid code, but stuck in a loop).</p> <p>The backtrace information printed on the reset can be used to find where the WDT happened specifically in your code, so you can find the issue (which could be the one @Benoit Blanchon noted). I have found <a href="https://github.com/me-no-dev/EspExceptionDecoder" rel="nofollow noreferrer">this exception decoder</a> to be very useful to translate the code to the functions in your code.</p> <p>Also worth noting that the 'garbled characters' after the WDT reset backtrace information is the bootloader startup message, which is fixed at 74880 baud, you can change baud rate of your serial terminal to see those (and 'garble' the other messages).</p> <p>(Info about watchdog timers and feeding below isn't directly relevant in this case, as @Juraj noted, but is left in for context)</p> <p><a href="https://e2e.ti.com/blogs_/b/powerhouse/posts/what-is-a-watchdog-timer-and-why-is-it-important" rel="nofollow noreferrer">This is an example document from TI introducing watchdog timers</a>. For the ESP8266, you might find <a href="https://techtutorialsx.com/2017/01/21/esp8266-watchdog-functions/" rel="nofollow noreferrer">this techtutorialsx document</a> more useful. In summary, you need to either turn off the watchdog, or issue periodic</p> <pre><code>ESP.wdtFeed(); </code></pre> <p>commands. Turning off the watchdog is an appealingly easy option, but it disables a really useful tool to help you to make your project/product handle unexpected conditions/bugs more gracefully, so I'd encourage you to learn how to use it and then <em>feed</em> it as above.</p> <p>(As @Benoit Blanchon noted, there are other issues on the implementation, which should be addressed, and perhaps deserve a separate post in code review. However I wanted to explain the reason for the reset you asked about, which isn't specifically JSON-related, and will continue to occur unless you take action as above)</p>
94857
|esp32|
PubSubClient constructor parameter type mismatch
2023-11-17T13:17:41.143
<p>I am just learning an Arduino so this is totally educational purpose call.</p> <p>I want to instantiate <code>PubSubClient</code> client with <code>WiFiClient</code> parameter.</p> <pre><code> #include &lt;WiFiClient.h&gt; #include &lt;PubSubClient.h&gt; WiFiClient *wifi = NULL; PubSubClient client(wifi); void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: } </code></pre> <p>compilation gives me back:</p> <pre><code>Compilation error: no matching function for call to /home/tepo/Arduino/libraries/PubSubClient/src/PubSubClient.h:116:4: note: candidate expects 0 arguments, 1 provided /home/tepo/Arduino/libraries/PubSubClient/src/PubSubClient.h:88:7: note: candidate: 'PubSubClient::PubSubClient(const PubSubClient&amp;)' class PubSubClient : public Print { ^~~~~~~~~~~~ /home/tepo/Arduino/libraries/PubSubClient/src/PubSubClient.h:88:7: note: no known conversion for argument 1 from 'WiFiClient*' to 'const PubSubClient&amp;' exit status 1 Compilation error: no matching function for call to 'PubSubClient::PubSubClient(WiFiClient*&amp;)' </code></pre> <p>and listing all the other constructors.</p> <p>type chain seems to hold: <code>class WiFiClient : public ESPLwIPClient</code> -&gt; <code>class ESPLwIPClient : public Client</code> -&gt; <code>class Client: public Stream</code></p> <p><code>PubSubClient</code> ctor:</p> <pre><code> PubSubClient(Client&amp; client); </code></pre> <p>so why is it not accepting a WifiClient as a parameter?</p>
<p>The issue you're encountering with the PubSubClient constructor in Arduino is related to how you're passing the WiFiClient object. You're currently using a pointer (WiFiClient *wifi), but the PubSubClient constructor expects a reference to a Client object, not a pointer.</p> <p>The WiFiClient class inherits from the Client, so it can be used with PubSubClient. However, you need to pass an instance of WiFiClient, not a pointer to an instance.</p> <p>Here's how you can correct your code:</p> <pre><code>#include &lt;WiFiClient.h&gt; #include &lt;PubSubClient.h&gt; WiFiClient wifi; PubSubClient client(wifi); void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: } </code></pre> <p>In this corrected version, wifi is an instance of WiFiClient, not a pointer. When you pass wifi to the PubSubClient constructor, it correctly matches the expected Client&amp; client parameter type.</p> <p>In C++ a pointer (WiFiClient *) is a variable that holds the memory address of an object. A reference (WiFiClient &amp;) is an alias for an object. The PubSubClient constructor expects a reference because it needs to interact with the Client object throughout its lifecycle, and references are generally safer and more straightforward to use in this context than pointers.</p>
94864
|arduino-nano|usb|arduino-nano-every|
Arduino Nano Every USB Connection not working
2023-11-18T08:26:00.783
<p>I have two original (designed and assembled in Italy) Arduino Nano Every Boards from a German Web Shop. They came sealed in original packaging. When I try to connect them to my PC, they don't power up.</p> <p>What I've tried so far:</p> <ul> <li>6 different USB cables</li> <li>1 Desktop PC with Arch Linux as well as Windows 10, all USB Ports available (front headers, back side motherboard)</li> <li>1 Laptop PC with Arch Linux</li> <li>1 Google Pixel 4 XL using a USB-B to -C adapter</li> </ul> <p>No combination of the USB cables with any of the aforementioned USB Ports / Machines / Operating Systems allow the Arduino Nano Every Boards to boot up (no LEDs flashing).</p> <p>I tried powering the boards using a 9V battery block on the V_in and GND pins, which works. I also tried powering the boards using a 9V battery block and then connecting the USB, but the aforementioned machines / operating systems do not recognize a new device connected via USB, despite the boards being powered (LEDs flashing).</p> <p>I also triple-checked the physical connection of the USB cables on both ends to be sure they are inserted properly. I can use the aforementioned USB cables, USB ports, machines, and operating systems to charge other devices or transfer data with other devices (like, e.g., smartphones, e-book readers, USB flash memory sticks, external hard drives, ...).</p> <p>What should I try next to get the Arduino Nano Every working?</p> <p>Please let me know which extra information I should provide. Thanks!</p> <p>Note: As far as I can see, using <code>lsusb</code> on Linux should always list connected USB devices, regardless of the groups my user's in. Nevertheless, I also loaded the <code>cdc_acm</code> module and added <code>SUBSYSTEMS==&quot;usb-serial&quot;, TAG+=&quot;uaccess&quot;</code> to a udev rule located at <code>/etc/udev/rules.d/01-ttyusb.rules</code>, and reloaded the udev rules, to no avail.</p>
<p>I've ordered an Arduino Nano (not &quot;Every&quot;) from a different web shop now, and it powers up as soon as I connect to USB. Since the Arduino Nano uses mini-USB (the Arduino Nano Every uses micro-USB), I'm using a different cable from the ones I tried on the two Arduino Nano Every boards I have. But given that I tried multiple cables that also work with other devices, I'm confident now that the two boards I have are just broken. I've had bad luck.</p>
94869
|array|memory|
Is there a maximum length of an array in ROM?
2023-11-18T16:52:31.130
<p>Consider the following code:</p> <pre class="lang-cpp prettyprint-override"><code> #include &lt;Arduino.h&gt; unsigned char testimage [] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ... many more rows ... 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; void setup() { Serial.begin(115200); while(!Serial); Serial.println(&quot;start&quot;); for (int i = 0; i &lt; 10; i++) { Serial.println((int)(testimage[i])); } Serial.println(&quot;stop&quot;); } void loop() {} </code></pre> <p>I found out that then the array gets a certain size, there is nothing being sent to the serial monitor. It looks like the entire program freezes. I do not even see the <code>start</code> message appear.</p> <p>I haven't tried to find the exact size, but it is somewhere between 4500 and 8000. (When sized around 4500, it works, when around 8000 it doesn't).</p> <p>When I do not address the array though, I do see the <code>start</code> and <code>stop</code> messages appear.</p> <p>I am using an Arduino ATMega2560.</p>
<p>It isn't clear whether you meant to put your array in ROM as your question implies, but the code you presented assigns it to RAM. That would surely restrict to your array to less than the 8K of of RAM minus whatever is needed by (globals + your libraries' statics + your code's statics + the stack).</p> <p>Update:</p> <blockquote> <p>I assumed the data section of the code would end up in ROM.</p> </blockquote> <p>In fact, an image of the <em>initialized data</em> section does become part of the ROM image. The initial values need to be saved somewhere so RAM can be initialized each time the program is(re-)started but it is not accessed from ROM during run-time. (Note we're not talking about PROGMEM data here, which <em>is</em> kept in ROM and accessed from there even at run-time.)</p>
94874
|arduino-ide|feather|
Feather M0 doesn't show up as a COM or Serial port
2023-11-19T03:17:00.553
<p>I am trying to upload a simple blink program on my Adafruit Feather M0 Radio with LoRa Radio Module to ensure that it connects to my PC. So far, I have:</p> <ul> <li>Gone through 4 data cables</li> <li>Tested for connection on 3 different devices (laptop on Windows 11, desktop on Windows 10, and computer running CentOS respectively)</li> <li>Followed the direction for using the board with the IDE <a href="https://learn.adafruit.com/adafruit-feather-m0-radio-with-lora-radio-module/setup" rel="nofollow noreferrer">here</a> and <a href="https://learn.adafruit.com/adafruit-feather-m0-radio-with-lora-radio-module/using-with-arduino-ide" rel="nofollow noreferrer">here</a></li> </ul> <p>But the Port submenu is greyed out and when it isn't, it just doesn't have the port that recognizes my Feather. When going into Device Manager, I can't see it in the list of devices even when I refresh.</p>
<p>Turns out the bootloader/USB firmware wasn't loaded in, which is why the double-tap reset wasn't working. I looked into the option of using another board as a programmer to get the bootloader in my Feather, but it proved to be more of a hassle than I thought so I'm just going to get a replacement. Hope this helps someone out in the future.</p>
94891
|arduino-nano|temperature-sensor|voltage|
Arduino read thermocouple Type K with ADS1115
2023-11-21T18:36:40.203
<p>I ordered a ADS1115 so I could measure temperature of a type K thermocouple, but I am not managing to get accurate readings. I had it working while having a normal A0 pin, but since the <a href="https://www.thermocoupleinfo.com/type-k-thermocouple.htm" rel="nofollow noreferrer">type K table</a> shows pretty low voltages, the 0-1023 scale is not accurate.</p> <p>When the thermocouple is at room temperature (around 22°c), it shows 00.0 millivolts on the multimeter (which I dont understand since it does not match with the table), and my program outputs a value of around -40 and a voltage of -0.005. When I heat it up until I measure 10.0 millivolts (around 250°c according table), the Arduino prints a value of 53 and a millivolts of 300.</p> <p>What am I doing wrong? I suspect something with the calculation, but I am not able to find out how I should do it, I know very little about millivolts.</p> <p>Can someone help me out what I am doing wrong here and what I should do?</p> <p>I have the thermocouple and ADS1115 connected as shown in the image below. <a href="https://i.stack.imgur.com/gy4yA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gy4yA.jpg" alt="wiring" /></a></p> <p>The code I am using is as following</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;Adafruit_ADS1X15.h&gt; const int analogFruitPin = 0; Adafruit_ADS1115 ads; void setup() { Serial.begin(9600); ads.begin(); ads.setGain(GAIN_FOUR); ads.setDataRate(RATE_ADS1115_860SPS); } void loop() { int sensorValue = ads.readADC_SingleEnded(analogFruitPin); float voltage = sensorValue * (5.0 / 32768.0); Serial.println(voltage,3); Serial.println(sensorValue); delay(500); } </code></pre>
<p>To simplify your thermocouple temperature sensor project, consider using an <a href="https://en.wikipedia.org/wiki/Analog-to-digital_converter" rel="nofollow noreferrer">ADC</a> which also contains a cold junction temperature sensor. <a href="https://www.adafruit.com/product/5165" rel="nofollow noreferrer">This product</a> from Adafuit.com integrates both into one package by using a Microchip.com <a href="https://www.microchip.com/en-us/product/mcp9601" rel="nofollow noreferrer">MCP9601 integrated circuit</a>.</p> <p>In short, thermocouples generate small amounts of voltage where dissimilar metals touch. This is true where the thermocouple wires are touching each other. And is also true where the thermocuple wires are touching the metal connecting them to the ADC circuit (commonly called the &quot;cold junction&quot;). To find the temperature where the thermocouple wires are touching we need to subtract the effects of the &quot;cold junction&quot;. To do that, we need to first know the temperature of the &quot;cold junction&quot;. We commonly do this with a second temperature sensor as it is a more practical (and portable) solution than a traditional zero centigrade ice bath (likely where the term &quot;cold junction&quot; came from).</p>
94928
|c++|interrupt|teensy|
Alternative to polling interrupt flag from main loop?
2023-11-27T09:47:31.407
<p>I am using an ISR, which is written to be as minimal as possible:</p> <pre class="lang-cpp prettyprint-override"><code>volatile bool interrupt1{}; void ISR1() { interrupt1 = true; } </code></pre> <p>The interrupt is handled by polling the interrupt1 variable in <code>loop()</code>:</p> <pre class="lang-cpp prettyprint-override"><code>if (interrupt1 == true) { // Do stuff interrupt1 = false; } </code></pre> <p>Even though the interrupt signal coming in on the gpio isn't polled, the method described above is instead polling the interrupt variable from <code>loop()</code>.</p> <p>As an alternative to the above, is it possible to use some kind of push logic on the software side whenever an interrupt occurs, instead of continuously polling the interrupt variable? I hesitate to handle the full task from the ISR, as it's performing a lot of things.</p> <p>What are my options here?</p>
<p>Since you tagged it Teensy: You could also reduce the priority of the interrupt, so that it can be interrupted by higher priority interrupts. Thus you can implement interrupts with longer durations without blocking important system functions.</p> <p>Here is an example using the GPT1 and GPT2 timers running at different priorities:</p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;Arduino.h&quot; #include &quot;TeensyTimerTool.h&quot; using namespace TeensyTimerTool; PeriodicTimer loPrioTimer(GPT1); PeriodicTimer hiPrioTimer(GPT2); void onLowPrioTimer() // some long task running from interrupt with low prio { Serial.printf(&quot; Start low prio isr @t=%d ms\n&quot;, millis()); for (int i = 0; i &lt; 10; i++) { Serial.printf(&quot; lowPriority task %d\n&quot;,i); delay(10); } Serial.println(&quot; Stop low prio isr&quot;); } void onHiPrioTimer() // high prio, will interrupt the low prio isr { Serial.printf(&quot;high priority @t=%d ms\n&quot;, millis()); } void setup() { while (!Serial) {} loPrioTimer.begin(onLowPrioTimer, 500ms); // GPT1 hiPrioTimer.begin(onHiPrioTimer, 50ms); // GPT2 NVIC_SET_PRIORITY(IRQ_GPT1, 128); // lowest prio NVIC_SET_PRIORITY(IRQ_GPT2, 16); // high prio } void loop() { } </code></pre> <p>which prints:</p> <pre><code>high priority @t=1057 ms high priority @t=1107 ms high priority @t=1157 ms high priority @t=1207 ms high priority @t=1257 ms high priority @t=1307 ms high priority @t=1357 ms high priority @t=1407 ms high priority @t=1457 ms high priority @t=1507 ms Start low prio isr @t=1507 ms lowPriority task 0 lowPriority task 1 lowPriority task 2 lowPriority task 3 lowPriority task 4 high priority @t=1557 ms lowPriority task 5 lowPriority task 6 lowPriority task 7 lowPriority task 8 lowPriority task 9 high priority @t=1607 ms Stop low prio isr high priority @t=1657 ms high priority @t=1707 ms high priority @t=1757 ms high priority @t=1807 ms high priority @t=1857 ms high priority @t=1907 ms high priority @t=1957 ms high priority @t=2007 ms Start low prio isr @t=2007 ms lowPriority task 0 lowPriority task 1 lowPriority task 2 lowPriority task 3 lowPriority task 4 high priority @t=2057 ms lowPriority task 5 lowPriority task 6 lowPriority task 7 lowPriority task 8 lowPriority task 9 high priority @t=2107 ms Stop low prio isr high priority @t=2157 ms high priority @t=2207 ms high priority @t=2257 ms high priority @t=2307 ms </code></pre> <p>This shows that the high priority timer (running at 50 ms interval) intercepts the low priority ISR which runs every 500 ms for about 100 ms.</p>
94935
|esp8266|
How to properly declare a random URL in ESPAsyncWebServer?
2023-11-27T17:49:25.870
<p>I'm trying to make a onetime URL with a random string to for example give a user onetime access to a house with a smart lock. I have a function to make a fixed 8-character string and the following code with the address that is randomly made.</p> <pre class="lang-cpp prettyprint-override"><code> controlserver.on(userurl, HTTP_GET, [](AsyncWebServerRequest *request){ if(urlactive==true){ if(request-&gt;authenticate(&quot;admin&quot;,&quot;admin&quot;)){ running=true; request-&gt;send(200); Serial.println(&quot;entered&quot;); urlactive=false; }else { return request-&gt;requestAuthentication(); } }else{ generateRandomString(); request-&gt;send(200, &quot;text/html&quot;, HTML_CSS_STYLING+ &quot;&lt;body&gt;&quot; &quot;&lt;br&gt;&lt;h1 style=\&quot;color:white; direction: rtl;\&quot;&gt;LInk is not valid!&lt;/h1&gt;&lt;/body&gt;&quot; ); } }); </code></pre> <p>the following function generates the <code>userurl</code> which is a <code>const char*</code> because the requirement of ESPAsyncWebServer library.</p> <pre class="lang-cpp prettyprint-override"><code>void generateRandomString() { const char specialChars[] = &quot;0123456789&quot;; const char letters[] = &quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;; String randomStringurl = &quot;&quot;; String keppmyuserpass = &quot;&quot;; randomStringurl += letters[random(26, 51)]; for (int i = 0; i &lt; 6; i++) { randomStringurl += letters[random(0, 51)]; } randomStringurl += specialChars[random(0, 9)]; Serial.println(randomStringurl); userurl = randomStringurl.c_str(); } </code></pre> <p>everything works fine when I enter the generated string that I convert into <code>const char*</code> using <code>c_str()</code> but I noticed an error when I copied the string partially by accident and too much to my surprise, I saw that the popup for the username and password showed up and I didn't expecte it, because I have a <code>notFound</code> function that will show an error when the entered URL doesn't exist. entered different strings but the problem is persistent. I think there is a problem with my string conversion to <code>const char*</code> using <code>c_str()</code>. but is it?</p> <p>Here is compliable code, the wifi mode is STA <code>WiFi.mode(WIFI_STA);</code> :</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;Arduino.h&gt; #ifdef ESP32 #include &lt;WiFi.h&gt; #include &lt;AsyncTCP.h&gt; #elif defined(ESP8266) #include &lt;ESP8266WiFi.h&gt; #include &lt;ESPAsyncTCP.h&gt; #endif #include &lt;ESPAsyncWebServer.h&gt; const char* userurl; String randomStringurl = &quot;&quot;; String keppmyuserpass = &quot;&quot;; AsyncWebServer server(80); const char* ssid = &quot;your_ssid&quot;; const char* password = &quot;your_password&quot;; const char* PARAM_MESSAGE = &quot;message&quot;; void notFound(AsyncWebServerRequest *request) { request-&gt;send(404, &quot;text/plain&quot;, &quot;Not found&quot;); } void generateRandomString() { const char specialChars[] = &quot;0123456789&quot;; const char letters[] = &quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;; randomStringurl = &quot;&quot;; keppmyuserpass = &quot;&quot;; randomStringurl += letters[random(26, 51)]; for (int i = 0; i &lt; 6; i++) { randomStringurl += letters[random(0, 51)]; } randomStringurl += specialChars[random(0, 9)]; Serial.println(randomStringurl); userurl = randomStringurl.c_str(); keppmyuserpass = randomStringurl; keppmyuserpass += letters[random(26, 51)]; keppmyuserpass += specialChars[random(0, 9)]; Serial.println(keppmyuserpass); } void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); if (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.printf(&quot;WiFi Failed!\n&quot;); return; } Serial.print(&quot;IP Address: &quot;); Serial.println(WiFi.localIP()); server.on(&quot;/&quot;, HTTP_GET, [](AsyncWebServerRequest *request){ request-&gt;send(200, &quot;text/plain&quot;, &quot;Hello, world&quot;); }); // Send a GET request to &lt;IP&gt;/get?message=&lt;message&gt; server.on(userurl, HTTP_GET, [] (AsyncWebServerRequest *request) { String message; if (request-&gt;hasParam(PARAM_MESSAGE)) { message = request-&gt;getParam(PARAM_MESSAGE)-&gt;value(); } else { message = &quot;No message sent&quot;; } request-&gt;send(200, &quot;text/plain&quot;, &quot;Hello, GET: &quot; + message); }); // Send a POST request to &lt;IP&gt;/post with a form field message set to &lt;message&gt; server.on(&quot;/post&quot;, HTTP_POST, [](AsyncWebServerRequest *request){ String message; if (request-&gt;hasParam(PARAM_MESSAGE, true)) { message = request-&gt;getParam(PARAM_MESSAGE, true)-&gt;value(); } else { message = &quot;No message sent&quot;; } request-&gt;send(200, &quot;text/plain&quot;, &quot;Hello, POST: &quot; + message); }); server.onNotFound(notFound); server.begin(); generateRandomString(); } void loop() { } </code></pre> <p>And here is the code from ESPAsyncWebServer.h library, that required the <code>url</code> to be a <code>const char* uri</code> what am I doing wrong?</p> <pre class="lang-cpp prettyprint-override"><code>AsyncCallbackWebHandler&amp; on(const char* uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest, ArUploadHandlerFunction onUpload, ArBodyHandlerFunction onBody); </code></pre> <p>New Update: So, I forgot to add a <code>&quot;/&quot;</code> before the URL, by doing so it solved the problem and here is the new function:</p> <pre class="lang-cpp prettyprint-override"><code>void generateRandomString() { const char specialChars[] = &quot;0123456789&quot;; const char letters[] = &quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;; randomStringurl = &quot;&quot;; keppmyuserpass = &quot;&quot;; randomStringurl +=&quot;/&quot;; randomStringurl += letters[random(26, 51)]; for (int i = 0; i &lt; 6; i++) { randomStringurl += letters[random(0, 51)]; } randomStringurl += specialChars[random(0, 9)]; Serial.println(randomStringurl); userurl = randomStringurl.c_str(); keppmyuserpass = randomStringurl; keppmyuserpass += letters[random(26, 51)]; keppmyuserpass += specialChars[random(0, 9)]; OTUPC = keppmyuserpass.c_str(); Serial.println(keppmyuserpass); } </code></pre> <p>But when I renew the link, the new link is not recognized and the first generated link was working. I think that @6v6gt might be right about this: &quot;Could it also be that the value of <code>userurl</code> must be known when <code>setup()</code> runs and the callback is registered?&quot;</p>
<p>6v6gt is right, that the URI for the handler must be known, when you use the <code>on()</code> function to set the handler. Inside the library, the <code>on()</code> function calls <code>setUri(const String&amp; uri)</code>, which which saves the <code>uri</code> in the classes interal <code>String</code> member variable. Thus the handle will not notice, if the originally used variable changes.</p> <p>I think the most elegant solution here would to be to use a regular expression for your handler URI (A regular expression is a string expression, that describes a template that can match other strings). That will let the handler match any URI, that fits that regex. Inside the handler you can then get the relevant part of the URI and check, if it is currently valid. If yes, you serve your content, otherwise you serve an error (for example a 404 Not Found).</p> <p>The third answer to <a href="https://stackoverflow.com/questions/35816454/setting-a-wildcard-in-esp8266webserver">this question</a> has a code snippet for this:</p> <pre><code>#include &lt;uri/UriRegex.h&gt; web_server.on(UriRegex(&quot;/home/([0-9]+)/first&quot;), HTTP_GET, [&amp;]() { web_server.send(200, &quot;text/plain&quot;, &quot;Hello from first! URL arg: &quot; + web_server.pathArg(0)); }); </code></pre> <p>The part of the URI, that's between the brackets, is the regex group, that is then made available via <code>web_server.pathArg(0)</code>. Your current code creates a string with one capital letter, 6 lower case letters and one digit, thus a regex group <code>([A-Z][a-z]{6}[0-9])</code>. You can read about how regex work online.</p> <p>When you look at <a href="https://github.com/me-no-dev/ESPAsyncWebServer#the-async-web-server" rel="nofollow noreferrer">this repo</a> of ESPAsyncWebServer (I'm not sure, which version you have), in the Readme right at the end under &quot;path variable&quot; you find this snippet:</p> <pre><code>server.on(&quot;^\\/sensor\\/([0-9]+)$&quot;, HTTP_GET, [] (AsyncWebServerRequest *request) { String sensorId = request-&gt;pathArg(0); }); </code></pre> <p>And a note, that regex support must be enabled.</p> <p>As I didn't test this, I suggest you try both methods and see, what works for you.</p>
94938
|ws2812|keypad|
Why is my variable giving the wrong value?
2023-11-27T22:14:55.163
<p>I'm making a program to show numbers in a WS2812 LED and TM1637. I'm also using a common 4x4 keypad.</p> <p>The WS2812 LED is just DIY with 25 x 10. Only two values can be displayed in a LED matrix just now. Without the LED part of the program, just the TM1637 and keypad connected to the Arduino, everything is fine. But adding the LED part of the program, I found out that entering 2 on keypad puts an erroneous value in my variable (-256 to exact). I tried debugging my code and found out that replacing the last iteration</p> <p><code>for (int i = 225; i &lt;= 231; i++) {</code></p> <p>with this line</p> <p><code>for (int i = 225; i &lt;= 230; i++) {</code></p> <p>mysteriously solved my problem. Any thoughts why this is happening?</p> <pre><code>#include &lt;Keypad.h&gt; #include &lt;Arduino.h&gt; #include &lt;TM1637Display.h&gt; #include &lt;Wire.h&gt; #include &lt;FastLED.h&gt; // Module connection pins (Digital Pins) #define CLK 2 #define DIO 3 #define NUM_LEDS 225 #define LED_PIN 12 CRGB leds[NUM_LEDS]; TM1637Display display(CLK, DIO); int DisplayNos=0; int KeyNum; char key; boolean NewKey = false; boolean DeleteAll=false; int SavedNum; // for 3 digits int ExtractDigit[3] = {0, 0, 0}; byte DigitPoint= 1; const byte ROWS = 4; //four rows const byte COLS = 4; //four columns char keys[ROWS][COLS] = { {'1','2','3','A'}, {'4','5','6','B'}, {'7','8','9','C'}, {'*','0','#','D'} }; byte rowPins[ROWS] = {11, 10, 9, 8}; //connect to the row pinouts of the keypad byte colPins[COLS] = {7, 6, 5, 4}; //connect to the column pinouts of the keypad //Create an object of keypad Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS ); void setup(){ Serial.begin(9600); FastLED.addLeds&lt;WS2812B, LED_PIN, GRB&gt;(leds, NUM_LEDS); FastLED.setBrightness(250); } void loop(){ int k; // uint8_t data[] = { 0x0, 0x0, 0x0, 0x0 }; // uint8_t blank[] = { 0x00, 0x00, 0x00, 0x00 }; display.setBrightness(0x0f); key = keypad.getKey();// Read the key // Print if key pressed if (key){ Serial.print(&quot;Key Pressed : &quot;); Serial.println(key); if (isDigit(key)){ KeyNum = key-48; Serial.println(key); Serial.println(DisplayNos); if (DigitPoint==1){ DisplayNos = 0; DisplayNos = KeyNum; } if (DigitPoint==2){ DisplayNos = KeyNum + (DisplayNos*10); } if (DigitPoint==3){ DisplayNos = KeyNum + (DisplayNos*10); } DigitPoint= DigitPoint+1; if (DigitPoint==4){ DigitPoint=1; } } if (key=='*'){ // asterist key cancels all char DisplayNos = 0; DigitPoint = 1; } if (key=='#'){ // asterisk key cancels all chars } NewKey = true; } display.showNumberDec(DisplayNos,false,3,0); if (NewKey == true){ DisplayLED(); FastLED.show(); } } void DisplayLED(){ int LedNum; byte digitnos; NewKey = false; ExtractDigit[3] = (DisplayNos/100)%10; ExtractDigit[2] = (DisplayNos/10)%10; ExtractDigit[1] = (DisplayNos)%10; for (int digitnos= 1; digitnos &lt;= 3; digitnos++) { LedNum = (digitnos-1)*9; if (ExtractDigit[digitnos] == 1){ leds[21-LedNum]= CRGB::Blue; leds[28+LedNum]= CRGB::Blue; leds[29+LedNum]= CRGB::Blue; leds[71-LedNum]= CRGB::Blue; leds[78+LedNum]= CRGB::Blue; leds[121-LedNum]= CRGB::Blue; leds[128+LedNum]= CRGB::Blue; leds[171-LedNum]= CRGB::Blue; leds[178+LedNum]= CRGB::Blue; leds[221-LedNum]= CRGB::Blue; leds[229+LedNum]= CRGB::Blue; leds[228+LedNum]= CRGB::Blue; leds[227+LedNum]= CRGB::Blue; } if (ExtractDigit[digitnos] == 2){ for (int i = 20; i &lt;= 22; i++) { leds[i-LedNum] = CRGB::Blue; } leds[26+LedNum]= CRGB::Blue; leds[30+LedNum]= CRGB::Blue; leds[68-LedNum]= CRGB::Blue; leds[74-LedNum]= CRGB::Blue; leds[76+LedNum]= CRGB::Blue; leds[122-LedNum]= CRGB::Blue; leds[128+LedNum]= CRGB::Blue; leds[170-LedNum]= CRGB::Blue; leds[180+LedNum]= CRGB::Blue; leds[218-LedNum]= CRGB::Blue; leds[225+LedNum]= CRGB::Blue; leds[226+LedNum]= CRGB::Blue; leds[227+LedNum]= CRGB::Blue; leds[228+LedNum]= CRGB::Blue; leds[229+LedNum]= CRGB::Blue; for (int i = 225; i &lt;= 231; i++) { leds[i-LedNum] = CRGB::Blue; } } } } </code></pre>
<pre><code>#define NUM_LEDS 225 ... CRGB leds[NUM_LEDS]; ... leds[225 + LedNum] = CRGB::Blue; leds[226 + LedNum] = CRGB::Blue; leds[227 + LedNum] = CRGB::Blue; leds[228 + LedNum] = CRGB::Blue; leds[229 + LedNum] = CRGB::Blue; </code></pre> <p>Your RGB matrix has 225 LEDs, but you're writing to RAM out of range and destroying their stored data and/or variables.</p>
94947
|esp32|compilation-errors|board|
Some of my <include> statements do not work
2023-11-28T12:08:34.463
<p>I'm trying to include the thing...</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;BLEDevice.h&gt; #include &lt;BLEServer.h&gt; #include &lt;BLEUtils.h&gt; #include &lt;BLE2902.h&gt; BLEServer* pServer = NULL; void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: } </code></pre> <p>But it simply doesn't see what's inside the .h files:</p> <pre><code>C:\Users\void\AppData\Local\Temp\.arduinoIDE-unsaved20231028-7016-1na7gr9.y1do\sketch_nov28b\sketch_nov28b.ino:6:1: error: 'BLEServer' does not name a type; did you mean 'Server'? BLEServer* pServer = NULL; // Pointer to the server ^~~~~~~~~ Server </code></pre> <p>May it be, I bought the wrong board? I've set it as lolin s2 mini.</p> <p><a href="https://i.stack.imgur.com/ws3LW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ws3LW.jpg" alt="enter image description here" /></a></p>
<p>Many of the <a href="https://en.wikipedia.org/wiki/ESP32#ESP32-xx_family" rel="nofollow noreferrer">ESP32 variants</a> have Bluetooth/BLE support. The ESP32-S2 board/module you're trying to use does not. <a href="https://www.espressif.com/sites/default/files/documentation/esp32-s2_datasheet_en.pdf" rel="nofollow noreferrer">The module</a> has WiFi, but not Bluetooth.</p> <p><a href="https://i.stack.imgur.com/X4d42.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X4d42.jpg" alt="Crop from original board image showing S2 markings highlighted." /></a></p> <p>So you need another board, Lolin seems to have an -S3 version of your board. But many other boards would work.</p> <p>The majority of the <code>&lt;BLEServer.h&gt;</code> header's contents are <a href="https://github.com/espressif/arduino-esp32/blob/2.0.14/libraries/BLE/src/BLEServer.h#L11" rel="nofollow noreferrer">conditionally compiled based on whether or not</a> <code>CONFIG_BLUEDROID_ENABLED</code> is <code>#define</code>d.</p> <p>And this only done for modules that have support for Bluetooth. The Lolin S3 version of the Mini would have Bluetooth support and in the configuration file it would use you can <a href="https://github.com/espressif/arduino-esp32/blob/2.0.14/tools/sdk/esp32s3/qio_qspi/include/sdkconfig.h#L178" rel="nofollow noreferrer">see it defined</a>. In the one for the S2 board you are trying to use <a href="https://github.com/espressif/arduino-esp32/blob/2.0.14/tools/sdk/esp32s2/qio_qspi/include/sdkconfig.h#L17-L18" rel="nofollow noreferrer">it is missing</a>.</p> <p>In effect, although you're including the header, it is as though it were blank. So no definition of the <code>BLEServer</code> type. It would have been nice if they'd handled this a different way, but this is not uncommon.</p>
94967
|arduino-uno|timers|time|keypad|
Unable to get keypad key in while loop
2023-11-29T19:58:25.947
<p>I'm a beginner into Arduino so I have a little problem where I'm trying to do a countdown on LCD using while loop but I'm also trying to get a key input inside that same while loop. Problem is that its hard to get a input in that while because there are delay because of timer. Tried to look around the internet for solution but didn't find one. If anybody got a good solution I would be great full if you post it :) Thanks again!</p> <p>Here is my code:</p> <pre><code>while (gameInProgress) { lcd.clear(); lcd.setCursor(0, 0); lcd.print(&quot;Until boom! &quot;); lcd.print(timer); lcd.setCursor(0, 1); lcd.print(passwordInputed); char key = keypad.getKey(); if (key &amp;&amp; gameInProgress) { passwordInputed += key; } analogWrite(buzzerPin, 145); delay(200); analogWrite(buzzerPin, 0); delay(800); timer--; if (timer == 0){ gameInProgress = false; lcd.clear(); lcd.setCursor(0, 0); lcd.print(&quot;Boom happend!&quot;); lcd.setCursor(0, 1); lcd.print(&quot;You lost :(&quot;); } } </code></pre>
<p>In general, when a program needs to perform two or more functions (for example, counting off seconds and reacting to a button press that could happen at any moment) a <a href="https://en.wikipedia.org/wiki/Finite-state_machine" rel="nofollow noreferrer">state machine</a> programming pattern will provide an optimal solution.</p> <p>Essentially, remove all calls to delay(). Instead, record the value returned from millis() outside the loop. If tracking a, say, 1 second (1000ms) interval, add 1000 to the recorded value. Each time through the loop, check if mills() is greater then the recorded value. When it is, change the state, add 1000 to the recorded value again and do what ever is needed when the state indicating 1 second has elapsed has changed. Now clear the state and wait for the cycle to repeat.</p> <p>As this loop with out calls to delay() is being executed as fast as possible, a scan for a button press can be added and the necessary reaction to that button press can be very responsive.</p> <p>Add states as needed for more complex behavior. Remember, in most state machines, outputs normally happen upon state changes. And there are no delays within the loop. Tests to trigger state changes are run as fast as possible each time through the loop.</p>
95023
|programming|
I need help for applying a logic to this code
2023-12-06T14:56:29.703
<p>Here's the code:</p> <pre><code>int softStart = A0; int enable = A1; int powerBTN = A2, powerState = HIGH, lastPowerState = HIGH; unsigned long lastDebounceTime = 0; unsigned long debounceDelay = 25; unsigned long powerTimer = 0; unsigned long powerHoldTimer = 0; bool softStartENB = 0; void setup() { Serial.begin(115200); pinMode(softStart, OUTPUT); pinMode(enable, OUTPUT); digitalWrite(enable, LOW); digitalWrite(softStart, LOW); pinMode(powerBTN, INPUT_PULLUP); } void loop() { int powerReading = digitalRead(powerBTN); if (powerReading != lastPowerState) { lastDebounceTime = millis(); } if ((millis() - lastDebounceTime) &gt; debounceDelay &amp;&amp; !softStartENB) { if (powerReading != powerState) { powerState = powerReading; if (powerState == HIGH) { digitalWrite(enable, !digitalRead(enable)); Serial.print(&quot;Normal start: &quot;); Serial.println(digitalRead(enable)); } } } if (powerReading == LOW) { powerTimer = millis() - lastDebounceTime; } else { powerTimer = 0; } if (powerTimer &gt;= 1000 &amp;&amp; millis() - powerHoldTimer &gt;= 2000) { softStartENB = 1; digitalWrite(enable, LOW); digitalWrite(softStart, HIGH); Serial.print(&quot;Soft start started: &quot;); Serial.println(digitalRead(softStart)); powerHoldTimer = millis(); } if (softStartENB &amp;&amp; lastPowerState == HIGH &amp;&amp; powerReading == LOW) { digitalWrite(enable, HIGH); delay(2000); digitalWrite(softStart, LOW); Serial.print(&quot;Soft start ended: &quot;); Serial.println(digitalRead(softStart)); softStartENB = 0; } lastPowerState = powerReading; } </code></pre> <p>So the logic is as this:</p> <p><a href="https://i.stack.imgur.com/bVWFI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bVWFI.png" alt="" /></a></p> <ol> <li>By pressing <code>powerBTN</code> the <code>enable</code> pin toggles.</li> <li>By holding <code>powerBTN</code> for 1 seconds <code>softStartENB</code> condition becomes true.</li> <li>When <code>softStartENB</code> is true, if I press <code>powerBTN</code> again it sets <code>enable</code> pin to high and after 2 seconds <code>softStart</code> to low.</li> </ol> <p>The problem is that after setting <code>softStartENB</code> to 0, <code>lastPowerState = powerReading</code> toggles <code>enable</code> pin to low but I want <code>enable</code> pin to stay high until I press <code>powerBTN</code> again to toggle it.</p> <ul> <li>How can I apply the described logic?</li> </ul>
<p>I solved the problem by using <a href="https://github.com/JChristensen/JC_Button" rel="nofollow noreferrer">JC_button</a> library:</p> <pre><code>#include &lt;JC_Button.h&gt; const byte softStart(A0), enable(A1); int powerStates = 0; bool enableState; Button powerBTN(A2); void setup() { Serial.begin(115200); powerBTN.begin(); pinMode(enable, OUTPUT); pinMode(softStart, OUTPUT); } void loop() { powerBTN.read(); Serial.println(powerStates); switch (powerStates) { case 0: if (powerBTN.wasReleased()) switchEnable(); else if (powerBTN.pressedFor(1000)) powerStates = 1; break; case 1: if (powerBTN.wasReleased()){ digitalWrite(enable, LOW); digitalWrite(softStart, HIGH); enableState = false; powerStates = 2; } break; case 2: if (powerBTN.wasReleased()){ digitalWrite(enable, HIGH); delay(2000); digitalWrite(softStart, LOW); enableState = true; powerStates = 0; } break; } } void switchEnable() { enableState = !enableState; digitalWrite(enable, enableState); } </code></pre>
95051
|recursion|
Recursive listing of sd card files
2023-12-09T20:39:08.437
<p>I'm working on a MP3 player and I want to list all files on the SD card.</p> <p>I have found this code on internet :</p> <pre class="lang-cpp prettyprint-override"><code>void displaySdCardContent(FileItem&amp; item, int numTabs) { for (int i = 0; i &lt; numTabs; i++) { Serial.print('\t'); } if (item.isDir) { Serial.println(item.name); for (FileItem fileElement : item.elements) { displaySdCardContent(fileElement, numTabs + 1); } } else { Serial.println(item.name); } } void displaySdCardContent(FileItem&amp; item, int numTabs) { for (int i = 0; i &lt; numTabs; i++) { Serial.print(&quot;...&quot;); } if (item.isDir) { Serial.println(item.name); for (FileItem&amp; fileElement : item.elements) { displaySdCardContent(fileElement, numTabs + 1); } } else { Serial.println(item.name); } } </code></pre> <p>It lists all the files but I can display only the first level directory. Here is my full code.</p> <pre class="lang-cpp prettyprint-override"><code>#define pushButton_pin 32 // Include required libraries #include &quot;Audio.h&quot; #include &quot;SD.h&quot; #include &quot;FS.h&quot; #include &lt;Wire.h&gt; #include &lt;TFT_eSPI.h&gt; #include &lt;SPI.h&gt; // microSD Card Reader connections #define SD_CS 5 #define SPI_MOSI 21 #define SPI_MISO 19 #define SPI_SCK 18 // I2S Connections #define I2S_DOUT 22 #define I2S_BCLK 26 #define I2S_LRC 25 // Create Audio object Audio audio; TFT_eSPI tft = TFT_eSPI(); //digitalWrite(TFT_BL, 1); int maxIndex; uint32_t Freq = 0; int Val; String Btn, SongName; String Status = &quot;Idle&quot;; bool state = true; bool Current_State = state; int Current_Millis; int Previous_Millis; int Debounce = 175; int Xindex = 0; int Yindex = 0; const uint8_t maxFileNameSize = 50; struct FileItem { bool isDir; char name[maxFileNameSize + 1]; FileItem* upDir; std::vector&lt;FileItem&gt; elements; }; File dir; String CurrDir; String NextDir; String Song; String Liste[50]; void setup() { pinMode(pushButton_pin, INPUT); setCpuFrequencyMhz(160); tft.init(); tft.setRotation(3); tft.fillScreen(TFT_BLACK); tft.setTextWrap(false); // Set microSD Card CS as OUTPUT and set HIGH pinMode(SD_CS, OUTPUT); digitalWrite(SD_CS, HIGH); // Initialize SPI bus for microSD Card SPI.begin(SPI_SCK, SPI_MISO, SPI_MOSI); // Start Serial Port Serial.begin(115200); // Start microSD Card if (!SD.begin(SD_CS)) { Serial.println(&quot;Error accessing microSD card!&quot;); while(true); } Serial.println(&quot;initialization done.&quot;); Serial.println(&quot;Creating structure of files&quot;); File root = SD.open(&quot;/&quot;); FileItem rootItem; if (strlen(root.name()) != 0) strncpy(rootItem.name, root.name(), maxFileNameSize); else strncpy(rootItem.name, &quot;/&quot;, maxFileNameSize); rootItem.name[maxFileNameSize] = '\0'; rootItem.isDir = true; readSdCard(root, rootItem); //Fin du listing Serial.println (&quot;----Disp----&quot;); displaySdCardContent(rootItem, 0); } void readSdCard(File dir, FileItem&amp; parentItem) { while (true) { File entry = dir.openNextFile(); if (!entry) { break; // no more files } FileItem item; item.isDir = entry.isDirectory(); strncpy(item.name, entry.name(), maxFileNameSize); // https://cplusplus.com/reference/cstring/strncpy/ item.name[maxFileNameSize] = '\0'; parentItem.elements.push_back(item); Serial.printf(&quot;Add %s to %s\n&quot;, item.name, parentItem.name); if (entry.isDirectory()) { readSdCard(entry, item); } } } void displaySdCardContent(FileItem&amp; item, int numTabs) { for (int i = 0; i &lt; numTabs; i++) { Serial.print(&quot;...&quot;); } if (item.isDir) { Serial.println(item.name); for (FileItem&amp; fileElement : item.elements) { displaySdCardContent(fileElement, numTabs + 1); } } else { Serial.println(item.name); } } </code></pre> <p>I have tried this to access the second level directories :</p> <pre class="lang-c prettyprint-override"><code> FileItem* subFolder = &amp;rootItem.elements.at(0); Serial.println (&quot;----Disp----&quot;); FileItem _subFolder= *subFolder; displaySdCardContent(_subFolder, 0); </code></pre> <p>But it doesn't work ...</p> <p>Here is what I get with the serial monitor :</p> <pre><code>23:36:23.419 -&gt; Add 11-Avalanche.mp3 to War Eternal 23:36:23.419 -&gt; Add 12-Down To Nothing.mp3 to War Eternal 23:36:23.419 -&gt; Add 13-Not Long For This World.mp3 to War Eternal 23:36:23.451 -&gt; Add folder.jpg to War Eternal 23:36:23.451 -&gt; Add Will To Power to Arch Enemy 23:36:23.483 -&gt; Add 01-Set Flame To The Night.mp3 to Will To Power 23:36:23.483 -&gt; Add 02-The Race.mp3 to Will To Power 23:36:23.515 -&gt; Add 03-Blood In The Water.mp3 to Will To Power 23:36:23.515 -&gt; Add 04-The World Is Yours.mp3 to Will To Power 23:36:23.515 -&gt; Add 05-The Eagle Flies Alone.mp3 to Will To Power 23:36:23.547 -&gt; Add 06-Reason To Believe.mp3 to Will To Power 23:36:23.547 -&gt; Add 07-Murder Scene.mp3 to Will To Power 23:36:23.579 -&gt; Add 08-First Day In Hell.mp3 to Will To Power 23:36:23.579 -&gt; Add 09-Saturnine.mp3 to Will To Power 23:36:23.612 -&gt; Add 10-Dreams Of Retribution.mp3 to Will To Power 23:36:23.643 -&gt; Add 11-My Shadow And I.mp3 to Will To Power 23:36:23.643 -&gt; Add 12-A Fight I Must Win.mp3 to Will To Power 23:36:23.675 -&gt; Add folder.jpg to Will To Power 23:36:23.675 -&gt; ----Disp---- 23:36:23.675 -&gt; Arch Enemy </code></pre> <p>Edit : Attributes item i can print in <code>displaySdCardContent()</code></p> <pre><code>14:58:54.763 -&gt; ----Disp---- 14:58:54.763 -&gt; name : Arch Enemy 14:58:54.763 -&gt; IsDir : 1 </code></pre> <p>Debug in <code>ReadsdCard</code></p> <pre><code>⸮⸮item name : 07. [Through The Eyes Of A Raven].mp3 item IsDir : 0 item size :0 parent item name : CD1 - Khaos Legions parent item IsDir : 1 Parent item size :7 Add 07. [Through The Eyes Of A Raven].mp3 to CD1 - Khaos Legions item name : 08. [Cruelty Without Beauty].mp3 item IsDir : 0 item size :0 parent item name : CD1 - Khaos Legions parent item IsDir : 1 Parent item size :8 Add 08. [Cruelty Without Beauty].mp3 to CD1 - Khaos Legions item name : 09. [We Are A Godless Entity].mp3 item IsDir : 0 item size :0 parent item name : CD1 - Khaos Legions parent item IsDir : 1 Parent item size :9 Add 09. [We Are A Godless Entity].mp3 to CD1 - Khaos Legions item name : 10. [Cult Of Chaos].mp3 item IsDir : 0 item size :0 parent item name : CD1 - Khaos Legions parent item IsDir : 1 Parent item size :10 Add 10. [Cult Of Chaos].mp3 to CD1 - Khaos Legions item name : 11. [Thorns In My Flesh].mp3 item IsDir : 0 item size :0 parent item name : CD1 - Khaos Legions parent item IsDir : 1 Parent item size :11 Add 11. [Thorns In My Flesh].mp3 to CD1 - Khaos Legions item name : 12. [Turn To Dust].mp3 item IsDir : 0 item size :0 parent item name : CD1 - Khaos Legions parent item IsDir : 1 Parent item size :12 Add 12. [Turn To Dust].mp3 to CD1 - Khaos Legions item name : 13. [Vengeance Is Mine].mp3 item IsDir : 0 item size :0 parent item name : CD1 - Khaos Legions parent item IsDir : 1 Parent item size :13 Add 13. [Vengeance Is Mine].mp3 to CD1 - Khaos Legions item name : 14. [Secrets].mp3 item IsDir : 0 item size :0 parent item name : CD1 - Khaos Legions parent item IsDir : 1 Parent item size :14 Add 14. [Secrets].mp3 to CD1 - Khaos Legions item name : CD2 - Kovered In Khaos item IsDir : 1 item size :0 parent item name : 2011 - Khaos Legions (2xCD, Ltd) parent item IsDir : 1 Parent item size :2 Add CD2 - Kovered In Khaos to 2011 - Khaos Legions (2xCD, Ltd) item name : 01. [Warning].mp3 item IsDir : 0 item size :0 parent item name : CD2 - Kovered In Khaos parent item IsDir : 1 Parent item size :1 Add 01. [Warning].mp3 to CD2 - Kovered In Khaos item name : 02. [Wings Of Tomorrow].mp3 item IsDir : 0 item size :0 parent item name : CD2 - Kovered In Khaos parent item IsDir : 1 Parent item size :2 Add 02. [Wings Of Tomorrow].mp3 to CD2 - Kovered In Khaos item name : 03. [The Oath].mp3 item IsDir : 0 item size :0 parent item name : CD2 - Kovered In Khaos parent item IsDir : 1 Parent item size :3 Add 03. [The Oath].mp3 to CD2 - Kovered In Khaos item name : 04. [The Book Of Heavy Metal].mp3 item IsDir : 0 item size :0 parent item name : CD2 - Kovered In Khaos parent item IsDir : 1 Parent item size :4 Add 04. [The Book Of Heavy Metal].mp3 to CD2 - Kovered In Khaos item name : Folder.jpg item IsDir : 0 item size :0 parent item name : 2011 - Khaos Legions (2xCD, Ltd) parent item IsDir : 1 Parent item size :3 Add Folder.jpg to 2011 - Khaos Legions (2xCD, Ltd) item name : War Eternal item IsDir : 1 item size :0 parent item name : Arch Enemy parent item IsDir : 1 Parent item size :4 Add War Eternal to Arch Enemy item name : 01-Tempore Nihil Sanat (Prelude in F minor).mp3 item IsDir : 0 item size :0 parent item name : War Eternal parent item IsDir : 1 Parent item size :1 Add 01-Tempore Nihil Sanat (Prelude in F minor).mp3 to War Eternal item name : 02-Never Forgive, Never Forget.mp3 item IsDir : 0 item size :0 parent item name : War Eternal parent item IsDir : 1 Parent item size :2 Add 02-Never Forgive, Never Forget.mp3 to War Eternal item name : 03-War Eternal.mp3 item IsDir : 0 item size :0 parent item name : War Eternal parent item IsDir : 1 Parent item size :3 Add 03-War Eternal.mp3 to War Eternal item name : 04-As The Pages Burn.mp3 item IsDir : 0 item size :0 parent item name : War Eternal parent item IsDir : 1 Parent item size :4 Add 04-As The Pages Burn.mp3 to War Eternal item name : 05-No More Regrets.mp3 item IsDir : 0 item size :0 parent item name : War Eternal parent item IsDir : 1 Parent item size :5 Add 05-No More Regrets.mp3 to War Eternal item name : 06-You Will Know My Name.mp3 item IsDir : 0 item size :0 parent item name : War Eternal parent item IsDir : 1 Parent item size :6 Add 06-You Will Know My Name.mp3 to War Eternal item name : 07-Graveyard Of Dreams.mp3 item IsDir : 0 item size :0 parent item name : War Eternal parent item IsDir : 1 Parent item size :7 Add 07-Graveyard Of Dreams.mp3 to War Eternal item name : 08-Stolen Life.mp3 item IsDir : 0 item size :0 parent item name : War Eternal parent item IsDir : 1 Parent item size :8 Add 08-Stolen Life.mp3 to War Eternal item name : 09-Time Is Black.mp3 item IsDir : 0 item size :0 parent item name : War Eternal parent item IsDir : 1 Parent item size :9 Add 09-Time Is Black.mp3 to War Eternal item name : 10-On And On.mp3 item IsDir : 0 item size :0 parent item name : War Eternal parent item IsDir : 1 Parent item size :10 Add 10-On And On.mp3 to War Eternal item name : 11-Avalanche.mp3 item IsDir : 0 item size :0 parent item name : War Eternal parent item IsDir : 1 Parent item size :11 Add 11-Avalanche.mp3 to War Eternal item name : 12-Down To Nothing.mp3 item IsDir : 0 item size :0 parent item name : War Eternal parent item IsDir : 1 Parent item size :12 Add 12-Down To Nothing.mp3 to War Eternal item name : 13-Not Long For This World.mp3 item IsDir : 0 item size :0 parent item name : War Eternal parent item IsDir : 1 Parent item size :13 Add 13-Not Long For This World.mp3 to War Eternal item name : folder.jpg item IsDir : 0 item size :0 parent item name : War Eternal parent item IsDir : 1 Parent item size :14 Add folder.jpg to War Eternal item name : Will To Power item IsDir : 1 item size :0 parent item name : Arch Enemy parent item IsDir : 1 Parent item size :5 Add Will To Power to Arch Enemy item name : 01-Set Flame To The Night.mp3 item IsDir : 0 item size :0 parent item name : Will To Power parent item IsDir : 1 Parent item size :1 Add 01-Set Flame To The Night.mp3 to Will To Power item name : 02-The Race.mp3 item IsDir : 0 item size :0 parent item name : Will To Power parent item IsDir : 1 Parent item size :2 Add 02-The Race.mp3 to Will To Power item name : 03-Blood In The Water.mp3 item IsDir : 0 item size :0 parent item name : Will To Power parent item IsDir : 1 Parent item size :3 Add 03-Blood In The Water.mp3 to Will To Power item name : 04-The World Is Yours.mp3 item IsDir : 0 item size :0 parent item name : Will To Power parent item IsDir : 1 Parent item size :4 Add 04-The World Is Yours.mp3 to Will To Power item name : 05-The Eagle Flies Alone.mp3 item IsDir : 0 item size :0 parent item name : Will To Power parent item IsDir : 1 Parent item size :5 Add 05-The Eagle Flies Alone.mp3 to Will To Power item name : 06-Reason To Believe.mp3 item IsDir : 0 item size :0 parent item name : Will To Power parent item IsDir : 1 Parent item size :6 Add 06-Reason To Believe.mp3 to Will To Power item name : 07-Murder Scene.mp3 item IsDir : 0 item size :0 parent item name : Will To Power parent item IsDir : 1 Parent item size :7 Add 07-Murder Scene.mp3 to Will To Power item name : 08-First Day In Hell.mp3 item IsDir : 0 item size :0 parent item name : Will To Power parent item IsDir : 1 Parent item size :8 Add 08-First Day In Hell.mp3 to Will To Power item name : 09-Saturnine.mp3 item IsDir : 0 item size :0 parent item name : Will To Power parent item IsDir : 1 Parent item size :9 Add 09-Saturnine.mp3 to Will To Power item name : 10-Dreams Of Retribution.mp3 item IsDir : 0 item size :0 parent item name : Will To Power parent item IsDir : 1 Parent item size :10 Add 10-Dreams Of Retribution.mp3 to Will To Power item name : 11-My Shadow And I.mp3 item IsDir : 0 item size :0 parent item name : Will To Power parent item IsDir : 1 Parent item size :11 Add 11-My Shadow And I.mp3 to Will To Power item name : 12-A Fight I Must Win.mp3 item IsDir : 0 item size :0 parent item name : Will To Power parent item IsDir : 1 Parent item size :12 Add 12-A Fight I Must Win.mp3 to Will To Power item name : folder.jpg item IsDir : 0 item size :0 parent item name : Will To Power parent item IsDir : 1 Parent item size :13 Add folder.jpg to Will To Power ----end of listing ---- rootItem.element[0] name : Arch Enemy rootItem.element[0] IsDir : 1 rootItem.element[0] size :0 </code></pre>
<p>The error is hard to see, but it is essentially in this original sequence (irrelevant statements omitted):</p> <pre class="lang-cpp prettyprint-override"><code> FileItem item; // ... parentItem.elements.push_back(item); // ... readSdCard(entry, item); } </code></pre> <p>The method <code>push_back()</code> <strong>copies</strong> the <code>item</code> to <code>elements</code>. Since at that moment <code>item</code> has no elements, the copy also has none. Later modifications of <code>item</code> do not change the copy.</p> <p>There are multiple alternatives to correct.</p> <p><strong>1. Recurse first, then push:</strong></p> <pre class="lang-cpp prettyprint-override"><code> FileItem item; // ... readSdCard(entry, item); } // ... parentItem.elements.push_back(item); </code></pre> <p>This way <code>item</code>'s <code>elements</code> vector collect its entries before the <code>push_back()</code>.</p> <p>However, the order of debug messages changes.</p> <p><strong>2. Recurse with the copy:</strong></p> <pre class="lang-cpp prettyprint-override"><code> FileItem item; // ... parentItem.elements.push_back(item); // ... readSdCard(entry, parentItem.elements.back()); } </code></pre> <p>In this case <code>readSdCard()</code> uses the copy of <code>item</code> in <code>parentItem</code>'s <code>elements</code> to collect the entries.</p>
95054
|serial|serial-data|
Why I always see while(serial.available() > 0) as the standard way of reading serial data?
2023-12-10T14:59:51.507
<p>Examples online always show this code to read bytes from the serial interface:</p> <pre><code>while(serial.available() &gt; 0) { char receivedByte = serial.read(); } </code></pre> <p>But I don't understand why it works.</p> <p>The read() operation &quot;removes&quot; a single byte from the queue, so the while loop should consume all the bytes from the queue.</p> <p>However, what guarantees that the incoming bytes are being pushed into the queue faster than the consuming process? I would imagine that any Arduino board is order of magnitude faster than a standard serial transmission, so it would starve the queue and effectively exit the while loop even though there are more incoming bytes to process. What am I missing here?</p>
<blockquote> <p>Examples online always show this code ...</p> </blockquote> <blockquote> <pre><code> while(serial.available() &gt; 0) { char receivedByte = serial.read(); } </code></pre> </blockquote> <p>You wouldn't have seen this &quot;always&quot; because it is <code>Serial</code> and not <code>serial</code>.</p> <p>Also the code you posted would be useless because it would repeatedly read into the same byte and do nothing with it.</p> <p>Assuming you are taking a bit of a licence with what you actually saw, it would be better for the code to gradually fill a buffer (and check for overflow) and then when a newline or other delimiter arrives, do something with it.</p> <p>You are right that you would, generally speaking, read faster than data arrives. You are also right that putting delays in is a silly way of trying to allow for that.</p> <p>I have <a href="https://arduino.stackexchange.com/questions/19756/how-does-serial-communications-work-on-the-arduino/19757#19757">an answer on this site</a> plus <a href="http://gammon.com.au/serial" rel="nofollow noreferrer">a page with suggested code</a> which goes into more detail.</p> <p>Those posts might help.</p>
95058
|arduino-ide|stm32|
Converting raw data of IIS2MDC into angle
2023-12-11T07:06:50.060
<p>I do not know that this is a good place for asking question but I have a 3 axis magnetometer IIS2MDC. I used this with Arduino. I downloaded the library <strong>IIS2MDC.h</strong> in Arduino IDE. I used example code of <strong>IIS2MDC.h</strong> library for reading magnetometer data. I have 3 axis raw data.</p> <p>My question is that how to convert magnetometer data into degrees? Is there any reference or solution for this?</p>
<p>It is likely the magnetometer needs to be calibrated before it can be used. Before calibration is applied to the magnetometer's output values, comparing any 2 of the 3 orthogonal sensors will be difficult.</p> <p>Search and learn the terms <a href="https://www.vectornav.com/resources/inertial-navigation-primer/specifications--and--error-budgets/specs-hsicalibration" rel="nofollow noreferrer">hard iron and soft iron distortion / calibration</a> with respect to magnetometers. Hard iron distortion is an offset error. Find the maximum (point a particular magnetometer toward magnetic north) and the minimum (point the same magnetometer away from magnetic north) values of one of the magnetometers. Calculate an offset value such that when applied the maximum and minimum magnitudes are the same. Soft iron distortion is a magnitude error. Find the maximum and minimum values for all 3 sensors. From this find the total range of all 3 sensors. Arbitrarily pick one of the sensors ranges and calculate magnitude adjustment values for the remaining sensor ranges such that after applying them all 3 sensors have the same range.</p> <p>At this point let us narrow the scope of the electronic compass to simplify the project. Let us constrain the compass to only be used on a table which is parallel to the surface of the earth. At which point we only need to use 2 of the sensors (the two that lie in the plane of the table).</p> <p>To calculate the angle the magnetometer is pointing with respect to magnetic north we take the arctangent of the ratio of the 2 magnetic sensor which lie in the plane of the table. However, this math function only gives us angles for half the desired angles. Fortunately, the C programming math library contains a special function <strong>atan2()</strong> which can return a full circle of angles (from <a href="https://www.oreilly.com/library/view/c-in-a/0596006977/re11.html" rel="nofollow noreferrer">here</a>):</p> <blockquote> <p>Synopsis. The atan2() function divides the first argument by the second and returns the arc tangent of the result, or arctan( y / x ) . The return value is given in radians, and is in the range -π ≤ atan2( y , x ) ≤ π.</p> </blockquote>
95089
|arduino-uno|arduino-ide|esp32|
Importing content of text file as string into Arduino code
2023-12-16T18:14:03.437
<p>Is there any macro for importing the content of a file (for example html code) located in the sketch folder as a string for the Arduino IDE during compilation time?</p>
<p>Try using the C++ Raw String Literal.</p> <p>It's in the form of</p> <pre class="lang-cpp prettyprint-override"><code>const char *myLiteralText=R&quot;abc123~~~( this is literal text which includes all spaces and newlines )abc123~~~&quot; </code></pre> <p>The <code>abc123~~~</code> is a delimiter.</p> <p>The test.h file must be modified by adding the first and last lines.</p> <p>Actually, the last line can be in the <code>test.ino</code> file after the #include line, so only the first line has to be added to the <code>test.h</code> file.</p> <p>Example at <a href="https://wokwi.com/projects/384484092370522113" rel="nofollow noreferrer">https://wokwi.com/projects/384484092370522113</a></p> <p>test.ino</p> <pre class="lang-cpp prettyprint-override"><code>void setup() { Serial.begin(9600); const char *index_html= #include &quot;test.h&quot; ; Serial.print(index_html); } void loop() {} </code></pre> <p>test.h</p> <pre><code>R&quot;html( &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;VIPSDK MONITOR&lt;/title&gt; &lt;meta http-equiv=&quot;refresh&quot; content=&quot;10&quot;&gt; &lt;/head&gt; &lt;style type=&quot;text/css&quot;&gt; &lt;/style&gt; &lt;/html&gt; )html&quot; </code></pre>
95116
|memory-usage|
Is it "safe" to use "new" keyword to instantize several sensor objects?
2023-12-20T21:39:47.017
<p>I've <a href="https://arduino.stackexchange.com/questions/77061/why-is-it-considered-bad-practice-to-use-the-new-keyword-in-arduino">read</a> that it is bad practice to use dynamic memory allocations on a microcontroller and I have a pretty good grasp of why.</p> <p>I am developing a custom PCB around an ATMega2560 and in my situation, I need to create 24 objects for <a href="https://github.com/Atlas-Scientific/Ezo_I2c_lib" rel="nofollow noreferrer">one kind of sensor</a> and 8 more for <a href="https://github.com/adafruit/Adafruit_MAX31865" rel="nofollow noreferrer">another</a>.</p> <p>With a small number of sensors, you might create objects like this:</p> <pre><code>Ezo_board PH = Ezo_board(99, &quot;PH&quot;); //create a PH circuit object, who's address is 99 and name is &quot;PH&quot; Ezo_board EC = Ezo_board(100, &quot;EC&quot;); //create an EC circuit object who's address is 100 and name is &quot;EC&quot; </code></pre> <p>But since I have so many and I want to loop through them I created a pointer array <code>Ezo_board *EC[maxEC];</code></p> <p>and in setup function I wrote:</p> <pre><code>for (uint8_t i = 0; i &lt; maxEC; i++) { EC[i] = new Ezo_board(i+11) //passing the I2C address which start at 11 and increment </code></pre> <p>I never delete the Ezo_board objects in the code. Is this a safe way to use dynamic memory allocation or is there a better way to do this while still maintaining ability to loop through the sensors in subsequent code?</p>
<p>The danger in using dynamic memory on embedded devices lies in <em>repeated</em> allocation &amp; de-allocation of chunks of memory. The memory allocator splits off a piece of memory for each allocation. When one is returned the de-allocator joins it - or should join it - with an adjacent free chunk, <em>if there is one</em>, to create a larger free chunk instead of two adjacent smaller ones. But that is a big 'if': 1) does the particular memory-manager even try to do that? and 2) in too many instances, it won't even be possible.</p> <p>The net result is that the memory pool becomes a bunch of small fragments that aren't join-able and aren't large enough to satisfy further requests.</p> <p>In your scenario, dynamic allocation at the start of the run with no further returns and re-alloacation, there is very little difference between it and static allocation, other than the static allocation would have be done at load-time, just before the run begins.</p> <p>Either way is fine in that case. If anyone else might ever look over your code, or if someday in the future you might come back to it and wonder whether this application might have created a fragmentation problem, then it's worth leaving a comment to make your intentions clear.</p> <p>I should add here that when I need dynamic allocation in an embedded system, I write my own memory allocator that never splits free memory. Instead, it simply hands out one buffer from a statically allocated array of fixed size buffers for any request up to that size (and returns a failure code otherwise). Memory is never split or joined, so it never gets fragmented. As long as the demand for buffers is predictable and you allocate enough of them to meet the maximum demand, your system won't fail for running out of memory.</p>
95146
|arduino-leonardo|windows|joystick|hid|
Joystick library not reading potentiometer
2023-12-27T04:35:50.953
<p>I am using Joystick Library to make a HOTAS system for flight simulators. When I load the test program I can get all the simulated controller inputs to register in windows. I can also get the value from my slide potentiometer to read in the serial monitor. But it will not change the value of the input function i pass it to. my guess is its the wrong kind of integer but I don't know very much about int types. Joystick.setThrottle has an int32_t as a parameter. Windows reads the value of throttle at 49% when its connected.</p> <p>What I have tried:</p> <p>changing the range (the default is 0 to 1023 I want it to be 0 to 255)</p> <p>changing the type of throttle_ to int, unsigned int, and int_32_t</p> <p>changing initAutoSendState</p> <p>using the pin number instead of the macro throttle passing throttle_ directly into Joystick.setThrottle without the updateThrottle function</p> <p>I have some programming experience from my high school class so I just tried different approaches but I am new to Arduino.</p> <pre><code>#include &quot;Joystick.h&quot; //define input pins #define throttle A0 //include hid, type, button count, hat count, x axis, y axis, z axis, Rx axis, Ry axis, Rz axis, rudder, Throttle, Accelerator, Brake, Steering Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID,JOYSTICK_TYPE_JOYSTICK, 0, 0, false, false, false, false, false, false, false, true, false, false, false); const bool initAutoSendState = true; int32_t throttle_ = 0; void updateThrottle (int32_t value) { Joystick.setThrottle(value); } void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(throttle, INPUT_PULLUP); Joystick.setThrottleRange(0, 255); } void loop() { // put your main code here, to run repeatedly: throttle_ = analogRead(throttle); throttle_ = map(throttle_, 0, 1023, 0, 255); updateThrottle(throttle_); Serial.print(throttle_); Serial.print(&quot;\n&quot;); } </code></pre>
<p>Looking through the examples turns out I needed to add <code>Joystick.begin();</code> to the setup</p>
95148
|arduino-uno|multiplexer|pcb-design|photoresistor|
Photoresistor Matrix has the same values
2023-12-27T10:29:33.687
<p>I'm a second-year System Engineer student who needs to make a project for class. I have a 4x4 matrix of photoresistors that goes to an analog digital multiplexer connected to an Arduino Uno. This setup is put in a box with a lid. The lid has a hole in the middle of the matrix. I want to calculate the angle of a light source depending on the photoresistors' readings. Basically, I want to recreate a Sattelite Sun Sensor. I have the following problem: all the photoresistors from a row have the same reading, even if I try to isolate one of them and shine a light on it. In the column, everything works well.</p> <p>This is my circuit on a 2 layers PCB: (C0-C15, SIG, S0-S3, EN are the pins of the CD74HC4067 Multiplexer)<br> <a href="https://i.stack.imgur.com/hgZGVl.png%3Cbr%3E" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hgZGVl.png%3Cbr%3E" alt="PCB Board" /></a> <a href="https://i.stack.imgur.com/St2mIl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/St2mIl.png" alt="Circuit Schematic" /></a></p> <p>Also, this is my code:</p> <pre><code>//Mux control pins int s0 = 11; int s1 = 10; int s2 = 9; int s3 = 8; //Mux in &quot;SIG&quot; pin int SIG_pin = 0; float values[4][4] = {0.0}; void setup(){ pinMode(s0, OUTPUT); pinMode(s1, OUTPUT); pinMode(s2, OUTPUT); pinMode(s3, OUTPUT); digitalWrite(s0, LOW); digitalWrite(s1, LOW); digitalWrite(s2, LOW); digitalWrite(s3, LOW); Serial.begin(9600); } void loop(){ //Loop through and read all 16 values for(int i = 0; i &lt; 4; ++i) for(int j = 0; j &lt; 4; ++j){ values[i][j] = readMux(i); delay(500); } Serial.println(&quot;-----Matrix-----&quot;); for(int i = 0; i &lt; 4; ++i){ for(int j = 0; j &lt; 4; ++j){ Serial.print(values[i][j]); Serial.print(&quot; &quot;); delay(100); } Serial.println(); } Serial.println(); Serial.print(calculateAngle()); Serial.println(); delay(1000); } float calculateAngle(){ const int dx[] = {-2, -1, 1, 2, -2, -1, 1, 2, -2, -1, 1, 2, -2, -1, 1, 2}; const int dy[] = {-2, -2, -2, -2, -1, -1, -1, -1, 1, 1, 1, 1, 2, 2, 2, 2}; float x = 0, y = 0; for(int i = 0; i &lt; 16; ++i){ x += dx[15 - i] * values[i / 4][i % 4]; y += dy[15 - i] * values[i / 4][i % 4]; } Serial.print(x); Serial.print(&quot; &quot;); Serial.print(y); Serial.print(&quot; &quot;); return atan2(y, x) * 180 / 3.14; } float readMux(int channel){ int controlPin[] = {s0, s1, s2, s3}; int muxChannel[16][4]={ {0,0,0,0}, //channel 0 {1,0,0,0}, //channel 1 {0,1,0,0}, //channel 2 {1,1,0,0}, //channel 3 {0,0,1,0}, //channel 4 {1,0,1,0}, //channel 5 {0,1,1,0}, //channel 6 {1,1,1,0}, //channel 7 {0,0,0,1}, //channel 8 {1,0,0,1}, //channel 9 {0,1,0,1}, //channel 10 {1,1,0,1}, //channel 11 {0,0,1,1}, //channel 12 {1,0,1,1}, //channel 13 {0,1,1,1}, //channel 14 {1,1,1,1} //channel 15 }; DDRB = 0; //loop through the 4 sig for(int i = 0; i &lt; 4; i ++) DDRB |= (1 &lt;&lt; i) &amp; muxChannel[channel][i]; //faster than digitalWrite(controlPin[i], muxChannel[channel][i]); delay(100); //read the value at the SIG pin int val = analogRead(SIG_pin); //convert the value in voltage float voltage = (val * 5.0) / 1024.0; //return the voltage return voltage; } </code></pre> <p>Example of a bogus reading:</p> <pre><code>-----Matrix----- 0.13 0.14 0.13 0.12 3.14 3.17 3.12 2.96 0.12 0.12 0.11 0.12 2.77 2.81 2.83 2.77 </code></pre> <p>What am I doing wrong? Did I make a mistake in my code or connecting everything together? Thank you for any help!<br></p>
<p>This is probably, because you don't actually set the MUX pins. The <code>DDRx</code> registers set the <strong>D</strong>ata <strong>D</strong>irection of the port pins. A 1 in there means, that the pin corresponding to that bit is set as output. A zero means, it is set as input. The output state of a pin is controlled by the <code>PORTx</code> registers. If the <code>DDRx</code> bits are set to input and the <code>PORTx</code> bits are set to 1, then the internal pullup resistor is activated.</p> <p>In setup you set all the MUX pins to OUTPUT and LOW, so <code>DDRB</code> with 1s and <code>PORTB</code> with zeros. Then in <code>readMux()</code> you are just setting bits in <code>DDRB</code> via the (overcomplicated) line:</p> <pre><code>DDRB |= (1 &lt;&lt; i) &amp; muxChannel[channel][i]; </code></pre> <p>So you are switching the pins between OUTPUT+LOW and INPUT+NO_PULLUP. Instead you should write to the <code>PORTB</code> register, which controls the output state of the port B pins.</p> <p>Also writing the mux channel can be done way easier. When you look at your array in <code>readMux()</code> you might notice, that the channel patters are just a binary number. So you have the following channel number to pattern relationship:</p> <pre><code>channel 0 --&gt; binary 0000 --&gt; decimal 0 channel 1 --&gt; binary 0001 --&gt; decimal 1 channel 2 --&gt; binary 0010 --&gt; decimal 2 channel 3 --&gt; binary 0011 --&gt; decimal 3 ... channel 10 --&gt; binary 1010 --&gt; decimal 10 ... </code></pre> <p>So instead of using the above overcomplicated line, you can just write the channel number to the 4 target bits of <code>PORTB</code>:</p> <pre><code>PORTB |= channel &amp; 0b00001111; </code></pre> <p>You don't even need to for loop for that. The <code>&amp; 0b00001111</code> part is only for cutting the channel number to only ever use the first 4 bits of the register (keeping it down between 0 and 15).</p>
95206
|arduino-uno|
"Done uploading" but Uno still running old sketch
2024-01-01T23:56:23.300
<p>So, this is my first experience, I bought new original Uno, trying write some code there and it stuck in running only one sketch.</p> <p>Tools-&gt;Boards is ok, Tools-&gt;Ports is ok.</p> <p>I try created new sketch from File-&gt;Examples-&gt;01. Basics-&gt;Blink and it uploaded successfully, but Uno still running old code and sending to Serial Monitor data (from empty A0, where was potentiometer)</p> <p>I tried reinstall Arduino App, trying on Windows, tried with only power (just 12v round port, without USB) and it still launch old sketch. When I plug Uno to Mac or Windows it immediately start spaming to Serial Monitor same data.</p> <p>Clicking, pressing, holding &quot;reset&quot; button with plug or unplug on smth else doesn't work.</p> <p>==============</p> <p>Here is my last code, which &quot;stuck&quot; on Uno right now:</p> <pre><code>const int myPin = A0; void setup() { Serial.begin(9600); pinMode(3, OUTPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); } void loop() { int sensorValue = analogRead(myPin); // Serial.print(&quot;Sensor value: &quot;); Serial.println(sensorValue); } </code></pre> <p>And proof that upload success: <a href="https://i.stack.imgur.com/xzb9a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xzb9a.png" alt="enter image description here" /></a></p> <p>Here is code of Blink from examples:</p> <pre><code>void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second } </code></pre> <p>And proof that upload success: <a href="https://i.stack.imgur.com/mJjjA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mJjjA.png" alt="enter image description here" /></a></p> <p>Here is my Uno without anything but with lighted TX port when I plug it into Mac/Windows (you can see that L/13 bulb light darker than should and I don't know why): <a href="https://i.stack.imgur.com/nN1A9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nN1A9.jpg" alt="enter image description here" /></a></p> <p>And here is unstoppable spaming in Serial Monitor by sketch from first code:</p> <pre><code>01:57:24.874 -&gt; 430 01:57:24.874 -&gt; 420 01:57:24.874 -&gt; 425 01:57:24.874 -&gt; 435 01:57:24.874 -&gt; 424 01:57:24.874 -&gt; 425 01:57:24.907 -&gt; 425 01:57:24.907 -&gt; 434 01:57:24.907 -&gt; 422 01:57:24.907 -&gt; 425 01:57:24.907 -&gt; 425 01:57:24.907 -&gt; 433 01:57:24.940 -&gt; 420 01:57:24.940 -&gt; 424 01:57:24.940 -&gt; 423 01:57:24.940 -&gt; 431 01:57:24.940 -&gt; 417 01:57:24.940 -&gt; 423 01:57:24.940 -&gt; 422 01:57:24.973 -&gt; 429 01:57:24.973 -&gt; 415 01:57:24.973 -&gt; 421 01:57:24.973 -&gt; 422 01:57:24.973 -&gt; 424 01:57:24.973 -&gt; 416 01:57:25.005 -&gt; 421 01:57:25.005 -&gt; 428 01:57:25.005 -&gt; 421 01:57:25.005 -&gt; 419 01:57:25.005 -&gt; 418 01:57:25.005 -&gt; 426 01:57:25.036 -&gt; 415 01:57:25.036 -&gt; 417 01:57:25.036 -&gt; 417 01:57:25.036 -&gt; 424 01:57:25.036 -&gt; 411 01:57:25.036 -&gt; 416 01:57:25.036 -&gt; 416 01:57:25.069 -&gt; 424 01:57:25.069 -&gt; 410 01:57:25.069 -&gt; 416 01:57:25.069 -&gt; 416 01:57:25.069 -&gt; 423 01:57:25.069 -&gt; 407 01:57:25.101 -&gt; 415 </code></pre> <p>=========== UPD: On IDE v. 1.8.19 I got this</p> <pre><code>Arduino: 1.8.19 (Mac OS X), Board: &quot;Arduino Uno&quot; Sketch uses 924 bytes (2%) of program storage space. Maximum is 32256 bytes. Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes. An error occurred while uploading the sketch avrdude: verification error, first mismatch at byte 0x0002 0x5d != 0x5c avrdude: verification error; content mismatch This report would have more information with &quot;Show verbose output during compilation&quot; option enabled in File -&gt; Preferences. </code></pre> <p>With checked show verbose during compilation and upload I got more:</p> <pre><code>Arduino: 1.8.19 (Mac OS X), Board: &quot;Arduino Uno&quot; /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/hardware -hardware /Users/mr_belogub/Library/Arduino15/packages -tools /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/tools-builder -tools /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/mr_belogub/Library/Arduino15/packages -built-in-libraries /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/libraries -libraries /Users/mr_belogub/Documents/Arduino/libraries -fqbn=arduino:avr:uno -vid-pid=2341_0043 -ide-version=10819 -build-path /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559 -warnings=none -build-cache /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_cache_275921 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avrdude.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -verbose /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/examples/01.Basics/Blink/Blink.ino /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/arduino-builder -compile -logger=machine -hardware /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/hardware -hardware /Users/mr_belogub/Library/Arduino15/packages -tools /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/tools-builder -tools /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/mr_belogub/Library/Arduino15/packages -built-in-libraries /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/libraries -libraries /Users/mr_belogub/Documents/Arduino/libraries -fqbn=arduino:avr:uno -vid-pid=2341_0043 -ide-version=10819 -build-path /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559 -warnings=none -build-cache /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_cache_275921 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avrdude.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -verbose /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/examples/01.Basics/Blink/Blink.ino Using board 'uno' from platform in folder: /Users/mr_belogub/Library/Arduino15/packages/arduino/hardware/avr/1.8.6 Using core 'arduino' from platform in folder: /Users/mr_belogub/Library/Arduino15/packages/arduino/hardware/avr/1.8.6 Detecting libraries used... /Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10819 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/Users/mr_belogub/Library/Arduino15/packages/arduino/hardware/avr/1.8.6/cores/arduino -I/Users/mr_belogub/Library/Arduino15/packages/arduino/hardware/avr/1.8.6/variants/standard /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/sketch/Blink.ino.cpp -o /dev/null Generating function prototypes... /Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10819 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/Users/mr_belogub/Library/Arduino15/packages/arduino/hardware/avr/1.8.6/cores/arduino -I/Users/mr_belogub/Library/Arduino15/packages/arduino/hardware/avr/1.8.6/variants/standard /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/sketch/Blink.ino.cpp -o /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/preproc/ctags_target_for_gcc_minus_e.cpp /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/tools-builder/ctags/5.8-arduino11/ctags -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/preproc/ctags_target_for_gcc_minus_e.cpp Compiling sketch... /Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10819 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/Users/mr_belogub/Library/Arduino15/packages/arduino/hardware/avr/1.8.6/cores/arduino -I/Users/mr_belogub/Library/Arduino15/packages/arduino/hardware/avr/1.8.6/variants/standard /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/sketch/Blink.ino.cpp -o /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/sketch/Blink.ino.cpp.o Compiling libraries... Compiling core... Using precompiled core: /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_cache_275921/core/core_arduino_avr_uno_7dc84736bec69d7a3f526b3465643c6f.a Linking everything together... /Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7/bin/avr-gcc -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.elf /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/sketch/Blink.ino.cpp.o /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/../arduino_cache_275921/core/core_arduino_avr_uno_7dc84736bec69d7a3f526b3465643c6f.a -L/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559 -lm /Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.elf /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.eep /Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy -O ihex -R .eeprom /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.elf /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex /Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7/bin/avr-size -A /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.elf Sketch uses 924 bytes (2%) of program storage space. Maximum is 32256 bytes. Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes. /Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/bin/avrdude -C/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.usbmodem1101 -b115200 -D -Uflash:w:/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex:i avrdude: Version 6.3-20190619 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/ Copyright (c) 2007-2014 Joerg Wunsch System wide configuration file is &quot;/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf&quot; User configuration file is &quot;/Users/mr_belogub/.avrduderc&quot; User configuration file does not exist or is not a regular file, skipping Using Port : /dev/cu.usbmodem1101 Using Programmer : arduino Overriding Baud Rate : 115200 AVR Part : ATmega328P Chip Erase delay : 9000 us PAGEL : PD7 BS2 : PC2 RESET disposition : dedicated RETRY pulse : SCK serial program mode : yes parallel program mode : yes Timeout : 200 StabDelay : 100 CmdexeDelay : 25 SyncLoops : 32 ByteDelay : 0 PollIndex : 3 PollValue : 0x53 Memory Detail : Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- eeprom 65 20 4 0 no 1024 4 0 3600 3600 0xff 0xff flash 65 6 128 0 yes 32768 128 256 4500 4500 0xff 0xff lfuse 0 0 0 0 no 1 0 0 4500 4500 0x00 0x00 hfuse 0 0 0 0 no 1 0 0 4500 4500 0x00 0x00 efuse 0 0 0 0 no 1 0 0 4500 4500 0x00 0x00 lock 0 0 0 0 no 1 0 0 4500 4500 0x00 0x00 calibration 0 0 0 0 no 1 0 0 0 0 0x00 0x00 signature 0 0 0 0 no 3 0 0 0 0 0x00 0x00 Programmer Type : Arduino Description : Arduino Hardware Version: 3 Firmware Version: 4.4 Vtarget : 0.3 V Varef : 0.3 V Oscillator : 28.800 kHz SCK period : 3.3 us avrdude: AVR device initialized and ready to accept instructions Reading | ################################################## | 100% 0.00s avrdude: Device signature = 0x1e950f (probably m328p) avrdude: reading input file &quot;/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex&quot; avrdude: writing flash (924 bytes): Writing | ################################################## | 100% 0.13s avrdude: 924 bytes of flash written avrdude: verifying flash memory against /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex: avrdude: load data flash data from input file /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex: avrdude: input file /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex contains 924 bytes avrdude: reading on-chip flash data: An error occurred while uploading the sketch Reading | ################################################## | 100% 0.13s avrdude: verifying ... avrdude: verification error, first mismatch at byte 0x0002 0x5d != 0x5c avrdude: verification error; content mismatch avrdude done. Thank you. </code></pre>
<p>It looks like your upload failed:</p> <pre><code>avrdude: verifying flash memory against /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex: avrdude: load data flash data from input file /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex: avrdude: input file /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex contains 924 bytes avrdude: reading on-chip flash data: An error occurred while uploading the sketch Reading | ################################################## | 100% 0.13s avrdude: verifying ... avrdude: verification error, first mismatch at byte 0x0002 0x5d != 0x5c avrdude: verification error; content mismatch </code></pre> <p>This was possibly related to your first sketch outputting to serial constantly. In future I suggest building in a delay before sending data constantly to serial (eg. <code>delay(500)</code>).</p> <p>Burning a new bootloader removed the problem sketch.</p> <p>Instead you could have held down the Reset button until the uploading started, and then released it. That would stop the original sketch from running.</p>
95232
|arduino-uno|arduino-mega|
LED control with a string variable
2024-01-04T18:37:53.527
<p>I would like to control three LEDs with a string variable using an Arduino Mega.</p> <p>I have connected the three LEDs to pins 10, 11 and 12 of the Arduino.</p> <p>If my string equals Red, the red LED should turn on. If my string equals Yellow, the yellow LED should turn on. If my string equals Green, the green LED should turn on.</p> <p>I wrote the following program, and I expect the following: When I type Red, I expect the Red LED to turn on, and so on for the others. But no LED turns on.</p> <p>You can check the following video: <a href="https://www.youtube.com/watch?v=MAnAc_t0OrM&amp;t=1583s" rel="nofollow noreferrer">https://www.youtube.com/watch?v=MAnAc_t0OrM&amp;t=1583s</a></p> <pre><code>int redPin=10, yellowPin=11, greenPin=12; String my_Color; String msg1=&quot;Which LED do you want to turn ON?&quot;; String msg2=&quot;Red, Yellow or Green?&quot;; String msg3=&quot;You chose LED:&quot;; void setup() { pinMode(redPin, OUTPUT); pinMode(yellowPin, OUTPUT); pinMode(greenPin, OUTPUT); Serial.begin(9600); } void loop() { Serial.println(msg1); Serial.println(msg2); while(Serial.available()==0) {} my_Color=Serial.readString(); Serial.print(msg3 ); Serial.println(my_Color); Serial.println('Red', BIN); Serial.println('my_Color',BIN); if(my_Color == &quot;Red&quot;) { Serial.print(&quot;Red True&quot;); digitalWrite(redPin,HIGH); digitalWrite(yellowPin,LOW); digitalWrite(greenPin,LOW); } if(my_Color==&quot;Yellow&quot;) { digitalWrite(redPin,LOW); digitalWrite(yellowPin,HIGH); digitalWrite(greenPin,LOW); } if(my_Color==&quot;Green&quot;) { digitalWrite(redPin,LOW); digitalWrite(yellowPin,LOW); digitalWrite(greenPin,HIGH); } } </code></pre> <p>Could anyone check the sketch and correct me?</p>
<p>This question originated on electronics.stackexchange.com, copying my answer from there: <p>There are three main areas where your system may be failing: the LEDs, the string input, and the logic evaluations. Right now it's a black box - you enter some input, and you don't see an output. But you have no idea where the system is failing between those two points. You should first narrow down to find which one the problem is. This is very good practice for learning how to debug systems in general.</p> <p>Start with the string input. After you read in the string from Serial, print it back out. Verify that it matches what you entered. (I expect this to be the problem. Like I said in my comment, your string is probably being read in as &quot;Red\r \n &quot;. Print the string twice, and if it prints &quot;Red&quot; twice with a line break in between, than that is your problem. You need to run my_Color.trim() to fix that.)</p> <p>Then, check the logic evaluations. Add a Serial.print() command with some string in it after each <strong>if</strong> evaluation. If your program prints out the string after you enter a valid LED color, than you know that your code is executing correctly. If not, there is some difference between the my_color String and the String you are checking it against.</p> <p>Thereafter, if it is still not working then the problem is with the LEDs. I don't have your circuit so I can't tell you what to debug there.</p>
95256
|arduino-uno|serial|
How does the serial monitor know where a string terminates when we use Serial.print instead of Serial.println?
2024-01-08T10:09:55.430
<p>EDIT: I thought I had to parse the things coming into the program but the speed it is running at makes it indistinguishable to the eye that the word is being printed piecewise.</p> <p>I am trying to create a serial monitor in rust using the serialport crate. I am using the following modification of blink code on the uno to test it:</p> <pre><code>void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT); Serial.begin(9600); } // the loop function runs over and over again forever void loop() { digitalWrite(LED_BUILTIN, HIGH); Serial.print(&quot;HIGH&quot;); delay(700); digitalWrite(LED_BUILTIN, LOW); Serial.print(&quot;LOW&quot;); delay(700); } </code></pre> <p>with println, I am thinking of just concatenating the received buffers and printing on receiving nl or cr. The serial monitor is doing a pretty good job with how it is able to discern a string if a has ended without NL or CR on running the code. How is it doing that? Here is my code right now:</p> <pre><code>use std::time::Duration; use serialport; fn main() { let open_port_config = serialport::new(&quot;/dev/cu.usbmodem1201&quot;, 9600).timeout(Duration::from_secs(10)); let open_port_result = open_port_config.open(); let mut port = match open_port_result { Ok(res) =&gt; res, Err(_) =&gt; panic!(&quot;Couldn't open the port&quot;) }; println!(&quot;Data bits: {}&quot;, port.data_bits().unwrap()); println!(&quot;Flow control: {}&quot;, port.flow_control().unwrap()); println!(&quot;Parity: {}&quot;, port.parity().unwrap()); println!(&quot;Stop bits: {}&quot;, port.stop_bits().unwrap()); loop { let mut serial_buf: [u8; 8] = [0; 8]; port.read(&amp;mut serial_buf[..]).expect(&quot;Found No data&quot;); let output = String::from_utf8(serial_buf.to_vec()).unwrap(); println!(&quot;{:?},{:?}: {}&quot;, serial_buf, output.trim_matches('\0'), output); } } </code></pre> <p>​</p>
<p>The answer is: It does not know. Or, if you want to look at it in a different way: Timing and chance.</p> <p>You simply never stumbled upon the case that you read the serial buffer on the PC side <em>in the exact moment when the Arduino is in the middle of writing to it</em>. That special case would be where you read and empty the buffer and output &quot;HI&quot; (followed by newline, because you add it in your code) on your serial monitor; then, during the next loop in your rust code, the remaining characters would be read, outputting &quot;GH&quot;.</p> <p>I'd say that you've been lucky that it always worked so far.</p> <p>The better way would be to always use <code>println</code> on the Arduinos side; and on the PCs side: the rust function to &quot;read until newline&quot; from a serial connection (I'm guessing it exists because it does exist in other standard libraries; I never worked with rust before). This way, you'll have in-band signalling for &quot;the next data block begins HERE&quot;.</p>
95276
|arduino-nano|esp32|sd-card|
I can't connect a microSD card
2024-01-11T18:07:09.270
<p>I can’t connect a microSD card to either the Arduino or the ESP32. It needs to be connected to the ESP32; I just tested it on the Arduino to see if it works at all.</p> <p>Equipment: ESP32 devkit v1, Arduino Nano, MicroSD card adapter, MicroSD card SanDisk 64gb eXFat.</p> <p>Software: Arduino IDE, library SdFat (version: 2.2.2). The sketch is an example from the sdfat library - (sdinfo).</p> <p>Connection to pin: SD adapter pin - CS, SCK, MOSI, MISO, VCC, GND<br /> Arduino to SD Adapter - (CS, D10) (SCK, D13) (MOSI, D11) (MISO, D12) (VCC, +5V) (GND, GND)<br /> ESP32 to SD Adapter - (CS, D27) (SCK, D14) (MOSI, D12) (MISO, D13) (VCC, VIN) (GND, GND)</p> <p>Result ESP32:</p> <pre><code>rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) configsip: 0, SPIWP:0xee clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00 mode:DIO, clock div:1 load:0x3fff0018,len:4 load:0x3fff001c,len:1044 load:0x40078000,len:8896 load:0x40080400,len:5828 entry 0x400806ac </code></pre> <p>Result Arduino:</p> <pre><code>SdFat version: 2.2.2 Assuming the SD is the only SPI device. Edit DISABLE_CS_PIN to disable an SPI device. Assuming the SD chip select pin is: 10 Edit SD_CS_PIN to change the SD chip select pin. type any character to start </code></pre> <p>These are the full port monitor results.</p>
<p>Found out what's wrong</p> <ol> <li>Common for connecting to any equipment</li> </ol> <p>SdFat doesn't work for me, I still don't understand what's wrong with this library so it's better to use standard SD library</p> <ol start="2"> <li>Common for connecting to any equipment</li> </ol> <p>SD card (no name, SDHC, 32 GB)</p> <p>Formatting an Sd card for an SD library (possibly for SdFat) should be in Fat32 with a msdos partition table<br /> I found the answer here (<a href="https://forum.arduino.cc/t/yet-another-sd-initialization-fail/286017" rel="nofollow noreferrer">https://forum.arduino.cc/t/yet-another-sd-initialization-fail/286017</a>)<br /> Due to an incorrect partition table, my card could not be read</p> <ol start="3"> <li><p>ESP32 pin connection<br /> ESP32 to MicroSD Adapter - (CS , D5) (SCK , D18) (MOSI , D23) (MISO , D19) (VCC , VIN) (GND , GND)</p> </li> <li><p>Arduino Pin Connection<br /> Arduino to MicroSD Adapter - (CS , D4) (SCK , D13) (MOSI , D11) (MISO , D12) (VCC , +5V) (GND , GND)</p> </li> </ol>
95288
|attiny85|platformio|
ATTiny85 pin definitions
2024-01-12T16:59:14.490
<p>I have been tearing my hair out on and off for two weeks trying to figure out pin definitions for the ATTiny85 in PlatformIO. My wiring is basically this:</p> <p><a href="https://i.stack.imgur.com/hvNzj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hvNzj.png" alt="ATTiny85 Wiper Test" /></a></p> <p>My sketch:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;Arduino.h&gt; #include &lt;avr/io.h&gt; #define WIPER PB2 void setup() { pinMode(WIPER, INPUT); } void loop() { int wiper_raw = analogRead(WIPER); int wiper = map(wiper_raw, 13, 1024, 0, 255); // show the actual value, probably not relevant to the question delay(100); } </code></pre> <p>(Showing the actual value is done by sending the mapped value over to a neopixel stick on the red channel, so basically turning the knob turns the stick from all the way off to brighter and brighter output of red.) The pot is connected to what should be physical pin 3, also known as PB4, also known as Arduino Pin 4, also known as ADC2, etc etc. (Using <a href="https://nerdytechy.com/wp-content/uploads/2021/01/attiny85-guide-pinout.png" rel="nofollow noreferrer">https://nerdytechy.com/wp-content/uploads/2021/01/attiny85-guide-pinout.png</a> as a guide but it's not any different from any other pinout listing I've seen.)</p> <p>In the sketch I'm referencing PB2, which VSCode tells me evaluates to <code>2</code>. That's physical pin 7. When I plugged the pot signal pin into pin 7, I got no response when manipulating the dial. So I started plugging it into all the other pins (except VCC, GND, and RESET) and the very last one I tried, pin 3, was the one that reacted to the changes on the pot.</p> <p>No pinout guide I've ever seen lists PB2 on physical pin 3. What am I doing wrong?</p>
<p>The macros such as <code>PB2</code> are defined in the avr-libc for accessing the bits of the raw I/O ports, with statements such as</p> <pre class="lang-cpp prettyprint-override"><code>PORTB |= _BV(PB2); // set PB2 as HIGH </code></pre> <p>They do not uniquely identify as pin: if you have more than one port (say, on an Uno), both <code>PB2</code> and <code>PC2</code> are equal to 2.</p> <p>If you use the Arduino core functions, you should not use these macros. Instead, use the plain numbers 0, 1... with <code>digitalRead()</code> and <code>digitalWrite()</code>, and the macros <code>A0</code>, <code>A1</code>... with <code>analogRead()</code>. Alternatively, with <code>analogRead()</code>, you can use the raw analog pin numbers 0, 1, which are interpreted as synonyms of <code>A0</code>, <code>A1</code>...</p> <p>Writing something like</p> <pre class="lang-cpp prettyprint-override"><code>analogRead(PB2); </code></pre> <p>is confusing, because you are using the avr-libc macro <code>PB2</code> in the wrong context. Furthermore, since this is the same as <code>analogRead(2);</code>, the Arduino core interprets it as equivalent to</p> <pre class="lang-cpp prettyprint-override"><code>analogRead(A2); </code></pre> <p>As the pinout image shows, Arduino pin <code>A2</code> is the same as ADC2, PB4 and physical pin 3.</p>
95307
|wifi|
Which WiFi module is able to host a custom web UI and can act as a station and AP?
2024-01-15T10:52:42.600
<p>I am an Arduino beginner. I am searching for a WiFi module that can act as a station and access point. It should have a external antenna.</p> <p>I need to upload a script that starts a web server, so I can host my custom UI where the user can enter his WLAN credentials. After the credentials are set, it should try to connect to that WLAN like in the example script below, from a YouTube video.</p> <p>I've <a href="https://arduino.stackexchange.com/questions/95194/esp8266-where-to-find-pin-assignment-guide-for-uploading-code">tried the ESP8266</a>, but uploading my script also overwrote the firmware.</p> <p>Someone suggested the &quot;Wemos D1 mini&quot;, but it does not have a big antenna and the one that I found with an antenna on Amazon has really really <a href="https://www.amazon.de/XTVTX-Antennenanschluss-esp8266-Serie-WiFi-Entwicklungsplatine-Entwicklungsplatine/dp/B09LCJJTBV/ref=sr_1_1?__mk_de_DE=%C3%85M%C3%85%C5%BD%C3%95%C3%91&amp;crid=UKEWJ8KNAW8R&amp;keywords=Mini%20WEMOS%20D1%20Pro-16%20Module%2B2.4G%20ESP8266%20Series%20WiFi%20Wireless%20Antenna%20Connector&amp;qid=1705316236&amp;sprefix=mini%20wemos%20d1%20pro-16%20module%2B2.4g%20esp8266%20series%20wifi%20wireless%20antenna%20connector%2Caps%2C69&amp;sr=8-1" rel="nofollow noreferrer">bad reviews</a>.</p> <pre class="lang-c prettyprint-override"><code>#include &lt;ESP8266WiFi.h&gt; #include &lt;ESP8266WebServer.h&gt; #include &lt;EEPROM.h&gt; ESP8266WebServer server(80); struct settings { char ssid[30]; char password[30]; } user_wifi = {}; void setup() { EEPROM.begin(sizeof(struct settings) ); EEPROM.get(0, user_wifi); WiFi.mode(WIFI_STA); WiFi.begin(user_wifi.ssid, user_wifi.password); byte tries = 0; while (WiFi.status() != WL_CONNECTED) { delay(1000); if (tries++ &gt; 30) { WiFi.mode(WIFI_AP); WiFi.softAP(&quot;Setup Portal&quot;, &quot;mrdiy.ca&quot;); break; } } server.on(&quot;/&quot;, handlePortal); server.begin(); } void loop() { server.handleClient(); } void handlePortal() { if (server.method() == HTTP_POST) { strncpy(user_wifi.ssid, server.arg(&quot;ssid&quot;).c_str(), sizeof(user_wifi.ssid)); strncpy(user_wifi.password, server.arg(&quot;password&quot;).c_str(), sizeof(user_wifi.password)); user_wifi.ssid[server.arg(&quot;ssid&quot;).length()] = user_wifi.password[server.arg(&quot;password&quot;).length()] = '\0'; EEPROM.put(0, user_wifi); EEPROM.commit(); server.send(200, &quot;text/html&quot;, &quot;&lt;!doctype html&gt;&lt;html lang='en'&gt;&lt;head&gt;&lt;meta charset='utf-8'&gt;&lt;meta name='viewport' content='width=device-width, initial-scale=1'&gt;&lt;title&gt;Wifi Setup&lt;/title&gt;&lt;style&gt;*,::after,::before{box-sizing:border-box;}body{margin:0;font-family:'Segoe UI',Roboto,'Helvetica Neue',Arial,'Noto Sans','Liberation Sans';font-size:1rem;font-weight:400;line-height:1.5;color:#212529;background-color:#f5f5f5;}.form-control{display:block;width:100%;height:calc(1.5em + .75rem + 2px);border:1px solid #ced4da;}button{border:1px solid transparent;color:#fff;background-color:#007bff;border-color:#007bff;padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem;width:100%}.form-signin{width:100%;max-width:400px;padding:15px;margin:auto;}h1,p{text-align: center}&lt;/style&gt; &lt;/head&gt; &lt;body&gt;&lt;main class='form-signin'&gt; &lt;h1&gt;Wifi Setup&lt;/h1&gt; &lt;br/&gt; &lt;p&gt;Your settings have been saved successfully!&lt;br /&gt;Please restart the device.&lt;/p&gt;&lt;/main&gt;&lt;/body&gt;&lt;/html&gt;&quot; ); } else { server.send(200, &quot;text/html&quot;, &quot;&lt;!doctype html&gt;&lt;html lang='en'&gt;&lt;head&gt;&lt;meta charset='utf-8'&gt;&lt;meta name='viewport' content='width=device-width, initial-scale=1'&gt;&lt;title&gt;Wifi Setup&lt;/title&gt; &lt;style&gt;*,::after,::before{box-sizing:border-box;}body{margin:0;font-family:'Segoe UI',Roboto,'Helvetica Neue',Arial,'Noto Sans','Liberation Sans';font-size:1rem;font-weight:400;line-height:1.5;color:#212529;background-color:#f5f5f5;}.form-control{display:block;width:100%;height:calc(1.5em + .75rem + 2px);border:1px solid #ced4da;}button{cursor: pointer;border:1px solid transparent;color:#fff;background-color:#007bff;border-color:#007bff;padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem;width:100%}.form-signin{width:100%;max-width:400px;padding:15px;margin:auto;}h1{text-align: center}&lt;/style&gt; &lt;/head&gt; &lt;body&gt;&lt;main class='form-signin'&gt; &lt;form action='/' method='post'&gt; &lt;h1 class=''&gt;Wifi Setup&lt;/h1&gt;&lt;br/&gt;&lt;div class='form-floating'&gt;&lt;label&gt;SSID&lt;/label&gt;&lt;input type='text' class='form-control' name='ssid'&gt; &lt;/div&gt;&lt;div class='form-floating'&gt;&lt;br/&gt;&lt;label&gt;Password&lt;/label&gt;&lt;input type='password' class='form-control' name='password'&gt;&lt;/div&gt;&lt;br/&gt;&lt;br/&gt;&lt;button type='submit'&gt;Save&lt;/button&gt;&lt;p style='text-align: right'&gt;&lt;a href='https://www.mrdiy.ca' style='color: #32C5FF'&gt;mrdiy.ca&lt;/a&gt;&lt;/p&gt;&lt;/form&gt;&lt;/main&gt; &lt;/body&gt;&lt;/html&gt;&quot; ); } } </code></pre>
<p>I will try to answer some of the misunderstandings, though this is not really a full answer, since I currently don't know what the exact problem is.</p> <p>First some terms:</p> <ul> <li><strong>Firmware</strong>: A firmware is a program running on a device. What we refer to as firmware is commonly the result of the compiled code, so a program in machine language. (Though sometimes people talk about firmware and mean the firmware code, which is not compiled at that time). In the world of microcontrollers, a firmware runs directly on a microcontroller's hardware (as opposed to a PC, where there is an OS in between). Thus only 1 firmware can run on the microcontroller at any given time. You cannot upload multiple firmwares to a microcontroller at the same time. Thus uploading a new one will overwrite the previous one.</li> <li><strong>Sketch</strong>: This is the Arduino term for your programs code. When you compile your sketch, the compiler will translate your code into assembler and then into machine language. The resulting file can then be uploaded to the microcontroller, where it overwrites the previous content of the flash memory.</li> <li><strong>SDK</strong>: A Software Development Kit is a set of code that provides easy to use access to important functionalities. The Arduino framework itself can be called a SDK. It provides easy to use access for commonly used microcontroller functionality, like digital and analog inputs. If you program an ESP through the Arduino IDE, it will have a copy of the ESP SDK, which gives easier access to complex things like Wifi handling. This ESP SDK comes from the company that makes the ESPs: Espressif. If someone wants to write a program for an ESP, like a firmware that speaks AT commands over serial that someone will get the ESP SDK from Espressif.</li> <li><strong>AT firmware</strong>: The AT firmware is not really different to your own program that you write/compile in the Arduino IDE. It uses the ESP SDK to handle things like Wifi. And it listens on the ESPs serial port for AT commands and reacts to them. You can write your own AT firmware, if you want to. This type of firmware is to provide simpler microcontrollers without Wifi hardware a network connection through Wifi. The simple microcontroller can send AT commands over serial to control the Wifi connection. Though this is of course inefficient and limited. It can be good to incorporate Wifi into an existing project, though when you try to do more complex stuff it is often better to ditch the simpler microcontroller and do everything directly on the ESP with your own custom firmware. No need for AT commands then.</li> </ul> <blockquote> <p>why the WiFi and AT commands are not working anymore after uploading a sketch</p> </blockquote> <p>As described above, you have created and uploaded your own firmware, by writing a sketch for the ESP in the Arduino IDE and uploading it. That program overwrites the one that was previously saved on the ESP. Thus the AT firmware is gone now. If you want to restore it, I'm sure you can find a fitting one for your board online and upload that again.</p> <p>Though from what you have written so far it seems to me that you don't really need an AT firmware. Programming a custom portal for Wifi credentials is something where you need your own firmware anyway. You are now sitting at the place of the AT firmware with your own program. You can tell it what to do by writing the corresponding code.</p> <blockquote> <p>Which WiFi module is able to host a custom web UI and can act as a station and AP?</p> </blockquote> <p>Every ESP board is capable of that as far as I know. Though I haven't seen an AT firmware yet that would support setting up a custom web UI. So you would need to write your own firmware.</p> <blockquote> <p>Someone suggested the &quot;Wemos D1 mini&quot;, but it does not have a big antenna and the one that I found with an antenna on Amazon has really really bad reviews.</p> </blockquote> <p>Most ESP boards are not made with an external antenna as a priority. Even the ones with a socket for an external antenna might require some work to set them from internal to external antenna (like desoldering a resistor). You might be able to find one that doesn't require this. The Wemos D1 mini pro unfortunately requires the desoldering of the 0Ohm resistor. That is set by the manufacturer, so any reseller would do the work themselves. Not many will do that.</p> <p>I cannot help you with finding such a board, as I don't know one (didn't need an external antenna yet). I would also just Google it.</p> <p>And for better quality you need to go to reputable sources. Amazon is often just as a bad gamble as directly buying from China, AliExpress or similar. If you buy there, expect the quality to be rather low and some boards might even be broken. Sometimes that is OK, sometimes not.</p> <p>Note: I'm really not an expert in RF, but honestly I would be surprised if connecting the antenna via a multiple meter-long cable wouldn't impact signal strength significantly. The ESP Wifi hardware is probably not built for driving the charge into such a long antenna. If this is the case it might be better to rethink your project design. You could put the ESP on top of the well (easily in reach of the Wifi network) and connect whatever you have down in the well from there. Or you could use another microcontroller handling the things in the well, connecting to the ESP via cable. Or if you absolutely need Wifi to connect down there, you might use an extender at the top of the well (can also be done by an ESP, if you don't want a full Wifi extender there). This very much depends on your exact requirements, so only a few ideas here.</p> <hr /> <p>Also I've noticed that in your <code>handlePortal()</code> function you are copying the SSID and password into the <code>user_Wifi</code> struct, but you are not actually changing the Wifi status. I would expect the code to do a change from AP to Station mode or reconnecting to the new Wifi.</p> <p>You are saving the credentials into EEPROM (which is just flash on an ESP) and retrieving it on the next startup. I've made that error many times myself: when the expected Wifi network from the ESP doesn't show up, are you sure that there are no valid Wifi credentials saved from your previous run?</p> <hr /> <p>I hope that this helps you a bit.</p>
95319
|esp8266|
ESP8266 I2C doesn't respond
2024-01-17T03:26:25.350
<p>I've got a huge problem using an ESP8266 from a Wemos D1 mini.</p> <p>I am using an STM32L073RZ to send a request to an ESP8266 to send me the time it has acquired from a WiFi connection.</p> <p>ESP code:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;ESP8266WiFi.h&gt; #include &lt;WiFiUdp.h&gt; #include &lt;NTPClient.h&gt; #include &lt;Wire.h&gt; // Zastąp poniższe wartości danymi Twojej sieci WiFi const char* ssid = &quot;:&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&quot;; const char* password = &quot;NOPE&quot;; #define Status D4 WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, &quot;europe.pool.ntp.org&quot;, 3600, 60000); void setup() { pinMode(D4, OUTPUT); // Pin odpowiedzialny za gotowość urządzenia do komunikacji przez I2C digitalWrite(D4, LOW); // Ustawiamy go na początku na &quot;0&quot;. Serial.begin(9600); WiFi.begin(ssid, password); while ( WiFi.status() != WL_CONNECTED ) { delay ( 500 ); Serial.print ( &quot;.&quot; ); } timeClient.begin(); Wire.begin(8); // Odpala D2 jako SDA i D1 jako SCL jako slave Wire.onRequest(sendTime); // Rejestracja funkcji zwrotnej, która zostanie wywołana, gdy urządzenie nadrzędne zażąda danych digitalWrite(D4, HIGH); // Tutaj konfiguracja z siecią jak i też konfiguracja z pinami i ustawienie I2C jest zakończone // i sygnalizowane stanem wysokim na D4 } void loop() { timeClient.update(); Serial.println(timeClient.getFormattedTime()); delay(1000); } void sendTime() { String time = timeClient.getFormattedTime(); Wire.write(time.c_str()); // Wysłanie czasu do urządzenia nadrzędnego będzie to razem 8 bajtów bo jeszcze znaki oddzielające. } </code></pre> <p>STM simple code :</p> <pre class="lang-cpp prettyprint-override"><code>xD = HAL_I2C_Master_Receive(&amp;hi2c2, 0x08&lt;&lt;1, czas, 8, 1000); </code></pre> <p>I tried everything. Adding pull ups, changing the GPIO speeds, etc.</p> <p>Here is what my logic analyser gave me:</p> <p><a href="https://i.stack.imgur.com/3x1cD.png" rel="nofollow noreferrer" title="Logic analyser output"><img src="https://i.stack.imgur.com/3x1cD.png" alt="Logic analyser output" title="Logic analyser output" /></a></p> <p>Still nothing. I've also checked which pins are the SDA and SCL which are D2 and D1. I've checked is the connection was correct and it should be, but still no response.</p> <p>I don't know anymore what is wrong or what is not.</p> <p>Schematic :</p> <p><a href="https://i.stack.imgur.com/sloVv.png" rel="nofollow noreferrer" title="Schematic"><img src="https://i.stack.imgur.com/sloVv.png" alt="Schematic" title="Schematic" /></a></p> <p>It is already powered so I didn't need to add 5 V and G pins to it, but I also tested with adding G pin to ground of the STM32, and also with 5 V to the 5 V of the STM32, but it still didn't work.</p>
<p>Both other answers are correct, but there is yet another problem with your design.</p> <p>As can be clearly seen from the logic analyzer output, the master runs its clock at 100kb/sec (the standard i2c rate). That leaves the slave ca. 5us to react. For a 80 MHz chip this might be quite a tight timing by itself and requires thorough inspection and optimization of code. But a UDP request into the big net? Seriously?!</p> <p>The only way it <em>might</em> work is if both parties could agree on a clock stretching. However, the i2c spec never defines precise timings for the stretched clock, so, the chances are, any master would probably break the session assuming the slave hung up long before the UDP request could be served.</p> <p>Therefore, such requests need to be split into two parts. First, the master asks the slave to initiate the process of measurement/exchange/computation/whatever. And second, after an appropriate delay, the master issues another request for the buffered result from slave.</p>
95335
|arduino-uno|arduino-ide|interrupt|compilation-errors|
I cannot resolve the errors with attachInterrupt() (error: invalid use of non-static member function)
2024-01-19T07:11:40.700
<p>I have been trying for days to get this code to work, but I cannot find a solution. Can anyone please help me find what I am missing here?</p> <p><strong>My sketch:</strong></p> <pre><code>#include &lt;ControlInterrupt.h&gt; const int commonPin = 2; const int buttonPins[] = {4,5,6,7,8}; ControlInterrupt controlInterrupt(commonPin, buttonPins); void setup() { // put your setup code here, to run once: controlInterrupt.configureCommon(); // Setup pins for interrupt attachInterrupt(digitalPinToInterrupt(commonPin), controlInterrupt.pressInterrupt, FALLING); controlInterrupt.begin(); } void loop() { // Empty } </code></pre> <p><strong>.h</strong></p> <pre><code>/* ControlInterrupt.h - A library for handling multiple buttons using a single interrupt. This is done by using an interrupt pin effectively as the ground, eliminating the need for additional components. Authors: Svizel_pritula 05/05/2019 TheCodeGeek 01/13/2024 */ #ifndef ControlInterrupt_h #define ControlInterrupt_h #include &lt;Arduino.h&gt; class ControlInterrupt { public: ControlInterrupt(int commonPin, int buttonPins[]); void begin(); void pressInterrupt(); void configureCommon(); void configureDistinct(); //void getCommand(int button); private: int _commonPin; //int _arrLength; int _buttonPins[]; }; #endif </code></pre> <p><strong>.cpp</strong></p> <pre><code>/* ControlInterrupt.h - A library for handling multiple buttons using a single interrupt. This is done by using an interrupt pin effectively as the ground, eliminating the need for additional components. Authors: Svizel_pritula 05/05/2019 TheCodeGeek 01/13/2024 */ #include &lt;Arduino.h&gt; #include &lt;ControlInterrupt.h&gt; unsigned long lastFire; ControlInterrupt::ControlInterrupt(int commonPin, int buttonPins[]) //, String commandOrder[] { _commonPin = commonPin; _arrLength = sizeof(buttonPins); _buttonPins[arrLength] = buttonPins; //_commandOrder[arrLength] = commandOrder; lastFire = 0; } void ControlInterrupt::begin() { Serial.begin(9600); } void ControlInterrupt::pressInterrupt() { // ISR if (millis() - lastFire &lt; 200) { // Debounce return; } lastFire = millis(); configureDistinct(); // Setup pins for testing individual buttons for (int i = 0; i &lt; (sizeof(buttonPins)/sizeof(int)); i++) { // Test each button for press if (!digitalRead(_buttonPins[i])) { getCommand(i); } } configureCommon(); // Return to original state } void ControlInterrupt::configureCommon() { pinMode(_commonPin, INPUT_PULLUP); for (int i = 0; i &lt; (sizeof(buttonPins)/sizeof(int)); i++) { pinMode(_buttonPins[i], OUTPUT); digitalWrite(_buttonPins[i], LOW); } } void ControlInterrupt::configureDistinct() { pinMode(_commonPin, OUTPUT); digitalWrite(_commonPin, LOW); for (int i = 0; i &lt; (sizeof(buttonPins)/sizeof(int)); i++) { pinMode(_buttonPins[i], INPUT_PULLUP); } } void ControlInterrupt::getCommand(int button) //String ControlInterrupt::getCommand(int button) { // Our handler String label; // This stores the string to print when controls are used Serial.print(button + 1); Serial.print(&quot;: &quot;); switch (button) { case 0: // statement label = &quot;UP&quot;; break; case 1: // statement label = &quot;DOWN&quot;; break; case 2: // statement label = &quot;CLEAR&quot;; break; case 3: // statement label = &quot;BACK&quot;; break; case 4: // statement label = &quot;LEFT&quot;; break; case 5: // statement label = &quot;ENTER&quot;; break; case 6: // statement label = &quot;RIGHT&quot;; break; default: // statement break; } Serial.print(label); //return label; } </code></pre>
<p>Member functions (here <code>pressInterrupt</code>) in C++ are special. You cannot use them where normal function is required (<code>atrachInterruot</code>). For explanations refer to any good book on C++.</p> <p>In this particular case, just strip all C++ specific constructs off. They make your code neither shorter nor understandable. All the data for ISR is global anyway.</p>
95351
|arduino-uno|interrupt|
I can't get my interrupt to control my project
2024-01-22T07:12:49.273
<p>I'm building a programmable resin pump for my resin printer. The goal is to enable the ability to set a print volume and print time provided by the printer. The pump would then pump at full speed to cover the build plate, then continue at a lower speed to continue filling until the print is complete. Other features would be added as needed.</p> <p>The problem that I'm having is that I can control everything by typing the commands on the keyboard, but the interrupt is not working as expected. Only the Left and Right commands work, but Up and Enter do nothing, and Down freezes the Arduino. The other buttons aren't connected yet.</p> <p>When commands are issued via keyboard or button successfully, the command is printed to the serial terminal, e.g. <code>#CMD# UP</code>.</p> <p>When using the buttons, Up and Enter (center) do nothing. Left and Right function properly, but Down begins to return the command and freezes the Arduino at <code>#C</code> so that even the keyboard commands do nothing.</p> <p>I've tried changing the byte values of Up, Down, Left, Right, and Enter to a number of different values, but no change was noted.</p> <p>What is going wrong?</p> <p><strong>Sketch</strong></p> <pre><code>/* Sub Menu https://lcdmenu.forntoh.dev/examples/submenu */ #include &lt;ItemSubMenu.h&gt; #include &lt;ItemInput.h&gt; #include &lt;LcdMenu.h&gt; #include &lt;utils/commandProccesors.h&gt; // #define is an alternate way of declaring a const #define LCD_ROWS 4 #define LCD_COLS 20 #define COMMONPIN 2 const byte BUTTONPINS[] = {4,5,6,7,8,9,10,11}; // Define commands as #define UP 56 // NUMPAD 8 #define DOWN 50 // NUMPAD 2 #define LEFT 52 // NUMPAD 4 #define RIGHT 54 // NUMPAD 6 #define ENTER 53 // NUMPAD 5 #define BACK 55 // NUMPAD 7 #define BACKSPACE 8 // BACKSPACE #define CLEAR 46 // NUMPAD . // Assigned based on the hardware directional buttons const byte commandOrder[8] = {UP,DOWN,LEFT,RIGHT,ENTER,BACK,BACKSPACE,CLEAR}; unsigned long lastFire = 0; extern MenuItem* autofillMenu[]; extern MenuItem* semiautofillMenu[]; extern MenuItem* manualfillMenu[]; extern MenuItem* selfcleanMenu[]; extern MenuItem* settingsMenu[]; #define CHARSET_SIZE 10 // Charset used for entering values char charset[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; // Active index of the charset int8_t charsetPosition = -1; // Declare the call back functions void setVolumeCallback(char* value); void setTimeCallback(char* value); // Define the main menu MAIN_MENU( ITEM_BASIC(&quot; *Resin Pump*&quot;), ITEM_SUBMENU(&quot;Auto Fill&quot;, autofillMenu), ITEM_SUBMENU(&quot;Semi-Auto Fill&quot;, semiautofillMenu), ITEM_SUBMENU(&quot;Manual Pump&quot;, manualfillMenu), ITEM_SUBMENU(&quot;Self-Clean&quot;, selfcleanMenu), ITEM_SUBMENU(&quot;Settings&quot;, settingsMenu)); // Auto-Fill SUB_MENU(autofillMenu, mainMenu, ITEM_BASIC(&quot; *Auto Fill*&quot;), ITEM_INPUT(&quot;Set Vol. (ml)&quot;, &quot;200&quot;, setVolumeCallback), // defalt to 200 ml (create a variable) ITEM_INPUT(&quot;Set Time&quot;, &quot;hh:mm&quot;, setTimeCallback), // default to 0's (create a variable) ITEM_BASIC(&quot;Start&quot;) // Execute the command to fill the vat over the specified time span. ); // Semi-Auto Fill SUB_MENU(semiautofillMenu, mainMenu, ITEM_BASIC(&quot; *Semi-Auto Fill*&quot;), ITEM_INPUT(&quot;Set Vol. (ml)&quot;, &quot;200&quot;, setVolumeCallback), // defalt to 200 ml (create a variable) ITEM_BASIC(&quot;Start&quot;) // Execute the command to fill the vat immediately. ); // Manual Control SUB_MENU(manualfillMenu, mainMenu, ITEM_BASIC(&quot; *Manual Control*&quot;), ITEM_BASIC(&quot;Fill (out)&quot;), // Execute the command to pump out, ITEM_BASIC(&quot;Empty (in)&quot;), // Execute the command to pump in, ITEM_BASIC(&quot;Stop&quot;) // Execute the command to stop pumping. ); // Self-Clean SUB_MENU(selfcleanMenu, mainMenu, ITEM_BASIC(&quot; *Self-Clean*&quot;), ITEM_BASIC(&quot;Start&quot;)); // Settings SUB_MENU(settingsMenu, mainMenu, ITEM_BASIC(&quot; *Settings*&quot;), ITEM_BASIC(&quot;Max Volume of Vat&quot;), ITEM_BASIC(&quot;Default Volume&quot;), ITEM_BASIC(&quot;Resin Amount&quot;), ITEM_BASIC(&quot;Resin Overhead&quot;), ITEM_BASIC(&quot;Pump Flow Rate&quot;), ITEM_BASIC(&quot;Default Pump Speed&quot;), ITEM_BASIC(&quot;Print Start Delay&quot;)); LcdMenu menu(LCD_ROWS, LCD_COLS); void setup() { Serial.begin(9600); configureCommon(); menu.setupLcdWithMenu(0x27, mainMenu); attachInterrupt(digitalPinToInterrupt(COMMONPIN), pressInterrupt, FALLING); } void loop() { // TODO: Remove check for serial and Serial.read, these will be replaced // by physical buttons and an interrupt. if (!Serial.available()) return; char command = Serial.read(); processMenuCommand(menu, command, charsetPosition, charset, CHARSET_SIZE, UP, DOWN, ENTER, BACK, CLEAR, BACKSPACE, LEFT, RIGHT); } /** * Define callbacks */ // setVolume is share with both Auto Fill and Semi-Auto Fill void setVolumeCallback(char* value) { // Do stuff with value Serial.print(F(&quot;# &quot;)); Serial.println(value); } void setTimeCallback(char* value) { // Do stuff with value Serial.print(F(&quot;# &quot;)); Serial.println(value); } /*** Begin Button Interrupt Watching ***/ void pressInterrupt() { // ISR if (millis() - lastFire &lt; 200) { // Debounce return; } lastFire = millis(); configureDistinct(); // Setup pins for testing individual buttons for (int i = 0; i &lt; sizeof(BUTTONPINS) / sizeof(int); i++) { // Test each button for press if (!digitalRead(BUTTONPINS[i])) { execCommand(i); } } configureCommon(); // Return to original state } void configureCommon() { pinMode(COMMONPIN, INPUT_PULLUP); for (int i = 0; i &lt; sizeof(BUTTONPINS) / sizeof(int); i++) { pinMode(BUTTONPINS[i], OUTPUT); digitalWrite(BUTTONPINS[i], LOW); } } void configureDistinct() { pinMode(COMMONPIN, OUTPUT); digitalWrite(COMMONPIN, LOW); for (int i = 0; i &lt; sizeof(BUTTONPINS) / sizeof(int); i++) { pinMode(BUTTONPINS[i], INPUT_PULLUP); } } void execCommand(int buttonIndex) { byte command = commandOrder[buttonIndex]; processMenuCommand(menu, command, charsetPosition, charset, CHARSET_SIZE, UP, DOWN, ENTER, BACK, CLEAR, BACKSPACE, LEFT, RIGHT); } </code></pre> <p>Schematic <a href="https://i.stack.imgur.com/VDj1L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VDj1L.png" alt="schematic" /></a></p>
<p>I resolved my problem by following the guidance that I linked to from digikey. My solution:</p> <pre><code>/* Sub Menu https://lcdmenu.forntoh.dev/examples/submenu */ #include &lt;ItemSubMenu.h&gt; #include &lt;ItemInput.h&gt; #include &lt;LcdMenu.h&gt; #include &lt;utils/commandProccesors.h&gt; // #define is an alternate way of declaring a const #define LCD_ROWS 4 #define LCD_COLS 20 #define DELAY 100 #define COMMONPIN 2 const byte BUTTONPINS[] = {4,5,6,7,8,9,10,11}; // Used to indicate if the interrupt was triggered // If not, set to -1. int8_t interruptTrigger = -1; // Define commands as #define UP 56 // NUMPAD 8 #define DOWN 50 // NUMPAD 2 #define LEFT 52 // NUMPAD 4 #define RIGHT 54 // NUMPAD 6 #define ENTER 53 // NUMPAD 5 #define BACK 55 // NUMPAD 7 #define BACKSPACE 8 // BACKSPACE #define CLEAR 46 // NUMPAD . // Assigned based on the hardware directional buttons const byte commandOrder[] = {UP,DOWN,LEFT,RIGHT,ENTER,BACK,CLEAR,BACKSPACE}; unsigned long lastFire = 0; extern MenuItem* autofillMenu[]; extern MenuItem* semiautofillMenu[]; extern MenuItem* manualfillMenu[]; extern MenuItem* selfcleanMenu[]; extern MenuItem* settingsMenu[]; #define CHARSET_SIZE 10 // Charset used for entering values char charset[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; // Active index of the charset int8_t charsetPosition = -1; // Declare the call back functions void setVolumeCallback(char* value); void setTimeCallback(char* value); // Define the main menu MAIN_MENU( ITEM_BASIC(&quot; *Resin Pump*&quot;), ITEM_SUBMENU(&quot;Auto Fill&quot;, autofillMenu), ITEM_SUBMENU(&quot;Semi-Auto Fill&quot;, semiautofillMenu), ITEM_SUBMENU(&quot;Manual Pump&quot;, manualfillMenu), ITEM_SUBMENU(&quot;Self-Clean&quot;, selfcleanMenu), ITEM_SUBMENU(&quot;Settings&quot;, settingsMenu)); // Auto-Fill SUB_MENU(autofillMenu, mainMenu, ITEM_BASIC(&quot; *Auto Fill*&quot;), ITEM_INPUT(&quot;Set Vol. (ml)&quot;, &quot;200&quot;, setVolumeCallback), // defalt to 200 ml (create a variable) ITEM_INPUT(&quot;Set Time&quot;, &quot;hh:mm&quot;, setTimeCallback), // default to 0's (create a variable) ITEM_BASIC(&quot;Start&quot;) // Execute the command to fill the vat over the specified time span. ); // Semi-Auto Fill SUB_MENU(semiautofillMenu, mainMenu, ITEM_BASIC(&quot; *Semi-Auto Fill*&quot;), ITEM_INPUT(&quot;Set Vol. (ml)&quot;, &quot;200&quot;, setVolumeCallback), // defalt to 200 ml (create a variable) ITEM_BASIC(&quot;Start&quot;) // Execute the command to fill the vat immediately. ); // Manual Control SUB_MENU(manualfillMenu, mainMenu, ITEM_BASIC(&quot; *Manual Control*&quot;), ITEM_BASIC(&quot;Fill (out)&quot;), // Execute the command to pump out, ITEM_BASIC(&quot;Empty (in)&quot;), // Execute the command to pump in, ITEM_BASIC(&quot;Stop&quot;) // Execute the command to stop pumping. ); // Self-Clean SUB_MENU(selfcleanMenu, mainMenu, ITEM_BASIC(&quot; *Self-Clean*&quot;), ITEM_BASIC(&quot;Start&quot;)); // Settings SUB_MENU(settingsMenu, mainMenu, ITEM_BASIC(&quot; *Settings*&quot;), ITEM_BASIC(&quot;Max Volume of Vat&quot;), ITEM_BASIC(&quot;Default Volume&quot;), ITEM_BASIC(&quot;Resin Amount&quot;), ITEM_BASIC(&quot;Resin Overhead&quot;), ITEM_BASIC(&quot;Pump Flow Rate&quot;), ITEM_BASIC(&quot;Default Pump Speed&quot;), ITEM_BASIC(&quot;Print Start Delay&quot;)); LcdMenu menu(LCD_ROWS, LCD_COLS); void setup() { Serial.begin(9600); configureCommon(); menu.setupLcdWithMenu(0x27, mainMenu); attachInterrupt(digitalPinToInterrupt(COMMONPIN), pressInterrupt, FALLING); } void loop() { // TODO: Remove check for serial and Serial.read, these will be replaced // by physical buttons and an interrupt. //if (!Serial.available()) return; //char command = Serial.read(); // If the trigger was set, ignore the serial command and redefine command to use the button command if (interruptTrigger &gt; -1) { char command = commandOrder[interruptTrigger]; processMenuCommand(menu, command, charsetPosition, charset, CHARSET_SIZE, UP, DOWN, ENTER, BACK, CLEAR, BACKSPACE, LEFT, RIGHT); interruptTrigger = -1; // Now that the trigger has been read, reset the trigger } } /** * Define callbacks */ // setVolume is share with both Auto Fill and Semi-Auto Fill void setVolumeCallback(char* value) { // Do stuff with value Serial.print(F(&quot;# &quot;)); Serial.println(value); } void setTimeCallback(char* value) { // Do stuff with value Serial.print(F(&quot;# &quot;)); Serial.println(value); } /*** Begin Button Interrupt Watching ***/ void pressInterrupt() { // ISR if (millis() - lastFire &lt; DELAY) { // Debounce return; } lastFire = millis(); configureDistinct(); // Setup pins for testing individual buttons for (int i = 0; i &lt; sizeof(BUTTONPINS); i++) { // Test each button for press if (!digitalRead(BUTTONPINS[i])) { interruptTrigger = i; // Set the interrupt trigger (reset elsewhere) /* NOT PICKING UP 4 (ENTER) */ } } configureCommon(); // Return to original state } void configureCommon() { pinMode(COMMONPIN, INPUT_PULLUP); for (int i = 0; i &lt; sizeof(BUTTONPINS); i++) { pinMode(BUTTONPINS[i], OUTPUT); digitalWrite(BUTTONPINS[i], LOW); } } void configureDistinct() { pinMode(COMMONPIN, OUTPUT); digitalWrite(COMMONPIN, LOW); for (int i = 0; i &lt; sizeof(BUTTONPINS); i++) { pinMode(BUTTONPINS[i], INPUT_PULLUP); } } </code></pre> <p>I also had to adjust my loops which were only allowing me to check 4 inputs. by excluding <code>/ sizeof(int)</code> I was able to detect all of the button presses. I'm sharing in case someone else runs into a similar situation.</p>
95359
|json|
ArduinoJson- unexplained '.size()' behaviour
2024-01-23T04:38:30.823
<p>I'm using an ESP8266, ArduinoJson v6.21.5. PlatformIO, and Vscode.</p> <p>The config file is saved and read correctly to the ESP8266's flash:</p> <pre class="lang-cpp prettyprint-override"><code>{ &quot;gen_pubTopic&quot;: [ &quot;DvirHome/Messages&quot;, &quot;DvirHome/log&quot;, &quot;DvirHome/debug&quot; ], &quot;subTopic&quot;: [ &quot;DvirHome/Light/int/KitchenLEDs&quot;, &quot;DvirHome/All&quot;, &quot;DvirHome/Light/int&quot;, &quot;DvirHome/Light&quot; ], &quot;pubTopic&quot;: [ &quot;DvirHome/Light/int/KitchenLEDs/Avail&quot;, &quot;DvirHome/Light/int/KitchenLEDs/State&quot; ] } </code></pre> <p>In case the config file is missing, <code>t[]</code>, <code>t2[]</code>, and <code>t3[]</code> are hard-coded to avoid boot failure.</p> <p>There are 3 <code>for</code> loops to read topics (from the config file or from hard-coded).</p> <p>The unexplained part is:</p> <ol> <li><p>The config file is saved and read as expected, and the code runs without any failure.</p> </li> <li><p>when the <code>for</code> loop contains <code>DOC[&quot;gen_pubTopic&quot;].size()</code> topics are read as expected, but when it is defined as <code>DOC[&quot;gen_pubTopic&quot;].size() |3</code> it crashes.</p> </li> <li><p><code>x</code>, <code>x2</code>, and <code>x3</code> are defined before each <code>for</code> loop. Again, once as defined in 2), still no change.</p> </li> <li><p>At some part it happened at the 3rd <code>for</code> loop, and sometimes at the 2nd <code>for</code> loop.</p> </li> <li><p>Printing <code>xi</code> values shows the expected values.</p> </li> <li><p>To make it clear - without using &quot;fallback annotation&quot; <code>|2</code> the code runs without crashing.</p> </li> <li><p>In all stages above - the fallback stage is not tested (meaning- config file is saved and read), and crashes happens when &quot;fallback annotation&quot; is added.</p> </li> </ol> <p>Appreciate any lead why.</p> <pre class="lang-cpp prettyprint-override"><code>void start_iot2(JsonDocument &amp;DOC) { /* Default values */ const char *t[] = {&quot;DvirHome/Messages&quot;, &quot;DvirHome/log&quot;, &quot;DvirHome/debug&quot;}; const char *t2[] = {&quot;DvirHome/Device&quot;, &quot;DvirHome/All&quot;}; const char *t3[] = {&quot;DvirHome/Device/Avail&quot;, &quot;DvirHome/Device/State&quot;}; uint8_t x = DOC[&quot;gen_pubTopic&quot;].size() | 3; for (uint8_t i = 0; i &lt; x; i++) { /* Some Code */ /* debug code */ Serial.print(&quot;Gen_&quot;); Serial.println(i); } uint8_t x2 = DOC[&quot;subTopic&quot;].size() | 2; for (uint8_t i = 0; i &lt; x2; i++) { /* Some Code */ /* debug code */ Serial.print(&quot;Sub_&quot;); Serial.println(i); } uint8_t x3 = DOC[&quot;pubTopic&quot;].size() | 2; for (uint8_t i = 0; i &lt; x3; i++) { /* Some Code */ /* debug code */ Serial.print(&quot;Pub_&quot;); Serial.println(i); } iot.start_services(extMQTT); } </code></pre> <p><strong>Edit_1</strong> Added <code>/*debug Code */</code> to for loops. At some point, the Serial Monitor showed:</p> <pre><code>Sub_0 Sub_1 Sub_2 Sub_3 Sub_4 Sub_5 </code></pre> <p>while the size of the <code>SubTopic</code> array is <strong>4</strong> and <code>|2</code> as default.</p>
<p>The &quot;fallback notation&quot; you're referring to is <a href="https://arduinojson.org/v6/api/jsonvariant/or/" rel="nofollow noreferrer"><code>JsonVariant::operator|</code></a> and only works for <a href="https://arduinojson.org/v6/api/jsonvariant/" rel="nofollow noreferrer"><code>JsonVariant</code></a>.</p> <p>In your program, you apply <code>|</code> to an <code>unsigned long</code>, so the <a href="https://en.cppreference.com/w/cpp/language/operator_arithmetic" rel="nofollow noreferrer">built-in bitwise &quot;or&quot; operator</a> applies. It performs a bit-by-bit &quot;or&quot; operation (for example <code>2 | 4</code> is <code>6</code>).</p> <p>In other words, <code>doc[&quot;key&quot;] | 4</code> behaves as you describe, but not <code>doc.size() | 4</code>.</p> <p>Unlike many other languages, you cannot use <a href="https://en.cppreference.com/w/cpp/language/operator_logical" rel="nofollow noreferrer">logical &quot;or&quot;</a> (<code>||</code>) either because it returns a boolean. So, if you want to make minimal changes to your code, you'll have to do something like this:</p> <pre class="lang-cpp prettyprint-override"><code>uint8_t x = DOC[&quot;gen_pubTopic&quot;].size(); if (!x) x = 3; </code></pre>
95361
|arduino-uno|rtc|
RTC DS1307 module not working
2024-01-23T10:15:04.597
<p>I have a problem with an RTC: it doesn't work correctly. When I try to read date or time, I only see the characters &quot;àààààààà&quot; or or the program is blocked.</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;Adafruit_GFX.h&gt; #include &lt;Adafruit_SSD1306.h&gt; #include &lt;RTClib.h&gt; DS1307 rtc; DateTime rtcTime; void setup() { //zainicjowanie generatora liczb losowych randomSeed(A0); Wire.begin(); rtc.begin(); } void loop() { rtcTime = rtc.now(); int mm = rtcTime.minute(); Serial.println(mm); delay(500); } </code></pre> <p>This function blocks my program:</p> <pre><code>String timeRTC(){ DateTime now = rtc.now(); String Hour = &quot;0&quot; + String(now.hour()); String Minutes = &quot;0&quot; + String(now.minute()); String Seconds = &quot;0&quot; + String(now.second()); if (Hour.length() == 3) { Hour = Hour.substring(1); } if (Minutes.length() == 3) { Minutes = Minutes.substring(1); } if (Seconds.length() == 3) { Seconds = Seconds.substring(1); } return Hour+&quot;:&quot;+Minutes+&quot;:&quot;+Seconds; } </code></pre> <p>I can't find what is causing this problem. I use an Arduino Uno in the WOKWI emulator.</p> <pre><code>String dateRTC(){ DateTime now = rtc.now(); String Day = &quot;0&quot; + String(now.day()); String Month = &quot;0&quot; + String(now.month()); String Year = String(now.year()); if (Day.length() == 3) { Day = Day.substring(1); } if (Month.length() == 3) { Month = Month.substring(1); } return Day+&quot;-&quot;+Month+&quot;-&quot;+Year; } String timeRTC(){ DateTime now = rtc.now(); String Hour = &quot;0&quot; + String(now.hour()); String Minutes = &quot;0&quot; + String(now.minute()); String Seconds = &quot;0&quot; + String(now.second()); if (Hour.length() == 3) { Hour = Hour.substring(1); } if (Minutes.length() == 3) { Minutes = Minutes.substring(1); } if (Seconds.length() == 3) { Seconds = Seconds.substring(1); } return Hour+&quot;:&quot;+Minutes+&quot;:&quot;+Seconds; } </code></pre> <p><a href="https://i.stack.imgur.com/t3ZVW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t3ZVW.jpg" alt="enter image description here" /></a></p>
<p>You don't have a problem with the RTC: if you call <code>Serial.begin()</code> in <code>setup()</code>, and remove everything in your <code>loop()</code> after <code>Serial.println(mm);</code>, the program works as expected. Your problem is elsewhere. Most likely you are corrupting memory, which leads to unpredictable behavior.</p> <p>Side note: if you switch to Adafruit's RTClib (called simply “RTClib” in the library manager), you can simplify <code>timeRTC()</code> to this:</p> <pre class="lang-cpp prettyprint-override"><code>String timeRTC() { return rtc.now().timestamp(DateTime::TIMESTAMP_TIME); } </code></pre>
95382
|atmega328|
Is it safe to leave an ATmega328PB's RX and TX pins unconnected?
2024-01-26T04:41:32.383
<p>I am using an ATmega328PB and was looking at Arduino's and others' schematics that use it. All schematics I've found use a serial chip to communicate between USB and TX &amp; RX. However, I do not need USB, and I plan to program the ATmega through ICSP.</p> <p>Is it safe to leave these pins unconnected or connect them directly to LEDs like some Arduino boards do (like in the photo)? I wasn't able to find clear information about it.</p> <p><a href="https://i.stack.imgur.com/lxT84.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lxT84.png" alt="enter image description here" /></a></p> <p>I apologize if this is a silly question. Thank you!</p>
<p>Look at these pins as any other I/O pin. There is nothing special about them, if you do not enable their special function, in your case USART0.</p> <p>This is what the data sheet says:</p> <blockquote> <p><strong>17.2.6 Unconnected Pins</strong></p> <p>If some pins are unused, it is recommended to ensure that these pins have a defined level. Even though most of the digital inputs are disabled in the deep sleep modes as described above, floating inputs should be avoided to reduce current consumption in all other modes where the digital inputs are enabled (Reset, Active mode and Idle mode).</p> <p>The simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up. In this case, the pull-up will be disabled during reset. If low power consumption during reset is important, it is recommended to use an external pull-up or pull-down. Connecting unused pins directly to V<sub>CC</sub> or GND is not recommended, since this may cause excessive currents if the pin is accidentally configured as an output.</p> </blockquote> <p>Therefore, if you do not use USART0 and do not need these LEDs, you can get away with no external circuitry. Just enable the internal pull-ups.</p>
95395
|esp32|eeprom|char|
Problem saving "char" variable to EEPROM on ESP32
2024-01-27T20:10:31.600
<p>I am making a project, in which I need to store the WiFi credentials to the EEPROM. For now, I am able to store a bool array in the EEPROM, but I am not able to store the <code>char</code> variables as the ESP32 crashes. I can't share the complete code since it is REALLY long, but here are the problematic functions:</p> <p>To save to the EEPROM:</p> <pre class="lang-cpp prettyprint-override"><code>//////////////////////////////////WORKING//////////////////////////////// void saveToEEPROM() { // Save the contents of the array in EEPROM memory for (int i = 0; i &lt; NUM_PARAM_ITEMS; i++) { EEPROM.write(i, menu_items_param_bool[i]); } ////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////NOT WORKING//////////////////////////////// // Save WiFi credentials in EEPROM if not empty int offset = NUM_PARAM_ITEMS; if (strlen(ssid1) &gt; 0) { for (int i = 0; i &lt; strlen(ssid1); i++) { EEPROM.write(offset + i, ssid1[i]); } offset += strlen(ssid1); EEPROM.write(offset, '\0'); // Null-terminate the SSID1 string } offset++; if (strlen(password1) &gt; 0) { for (int i = 0; i &lt; strlen(password1); i++) { EEPROM.write(offset + i, password1[i]); } offset += strlen(password1); EEPROM.write(offset, '\0'); // Null-terminate the Password1 string } offset++; if (strlen(ssid2) &gt; 0) { for (int i = 0; i &lt; strlen(ssid2); i++) { EEPROM.write(offset + i, ssid2[i]); } offset += strlen(ssid2); EEPROM.write(offset, '\0'); // Null-terminate the SSID2 string } offset++; if (strlen(password2) &gt; 0) { for (int i = 0; i &lt; strlen(password2); i++) { EEPROM.write(offset + i, password2[i]); } offset += strlen(password2); EEPROM.write(offset, '\0'); // Null-terminate the Password2 string } EEPROM.commit(); // Don't forget to call the commit() function to save the data to EEPROM } </code></pre> <p>To read from the EEPROM:</p> <pre class="lang-cpp prettyprint-override"><code>void readFromEEPROM() { //////////////////////////////////WORKING//////////////////////////////// // Read the contents of the EEPROM memory and restore it to the array for (int i = 0; i &lt; NUM_PARAM_ITEMS; i++) { menu_items_param_bool[i] = EEPROM.read(i); } //////////////////////////////////NOT WORKING////////////////////////////////// // Read WiFi credentials from EEPROM if not empty int offset = NUM_PARAM_ITEMS; // Read SSID1 int ssid1Length = EEPROM.read(offset); if (ssid1Length &gt; 0) { for (int i = 0; i &lt; ssid1Length; i++) { ssid1[i] = (char)EEPROM.read(offset + i + 1); } ssid1[ssid1Length] = '\0'; // Null-terminate the SSID1 string Serial.print(&quot;SSID1: &quot;); Serial.println(ssid1); } offset += ssid1Length + 1; // Read Password1 int password1Length = EEPROM.read(offset); if (password1Length &gt; 0) { for (int i = 0; i &lt; password1Length; i++) { password1[i] = (char)EEPROM.read(offset + i + 1); } password1[password1Length] = '\0'; // Null-terminate the Password1 string Serial.print(&quot;PASSWORD1: &quot;); Serial.println(password1); } offset += password1Length + 1; // Read SSID2 int ssid2Length = EEPROM.read(offset); if (ssid2Length &gt; 0) { for (int i = 0; i &lt; ssid2Length; i++) { ssid2[i] = (char)EEPROM.read(offset + i + 1); } ssid2[ssid2Length] = '\0'; // Null-terminate the SSID2 string Serial.print(&quot;SSID2: &quot;); Serial.println(ssid2); } offset += ssid2Length + 1; // Read Password2 int password2Length = EEPROM.read(offset); if (password2Length &gt; 0) { for (int i = 0; i &lt; password2Length; i++) { password2[i] = (char)EEPROM.read(offset + i + 1); } password2[password2Length] = '\0'; // Null-terminate the Password2 string Serial.print(&quot;PASSWORD2: &quot;); Serial.println(password2); } } </code></pre> <p>And the variables to save and read are:</p> <pre class="lang-cpp prettyprint-override"><code>char ssid1[32] = &quot;ssid1&quot;; // SSID of the first WiFi network char password1[64] = &quot;password1&quot;; // Password of the first WiFi network char ssid2[32] = &quot;ssid2&quot;; // SSID of the second WiFi network char password2[64] = &quot;password2&quot;; // Password of the second WiFi network </code></pre> <p>Can anybody help me?</p>
<p>There are multiple issues with your code.</p> <ol> <li>If <code>strlen(anystring)</code> is zero, you write nothing, but increment <code>offset</code>.</li> <li>You try to read the lengths of the strings from EEPROM, but you never write them there.</li> </ol> <p>Some things are complicated and can be simplified.</p> <ol> <li>You don't need to explicitly write <code>'\0'</code> (end-of-string marker), since each of your strings already includes it.</li> <li>Increment <code>offset</code> directly in the course.</li> </ol> <p>This is a possible corrected solution. It uses the length and the end-of-string marker for each stored string.</p> <pre class="lang-cpp prettyprint-override"><code> // Write anystring int anystringLength = strlen(anystring); EEPROM.write(offset, anystringLength); offset++; for (int i = 0; i &lt;= anystringLength; i++) { EEPROM.write(offset, anystring[i]); offset++; } </code></pre> <pre class="lang-cpp prettyprint-override"><code> // Read anystring int anystringLength = EEPROM.read(offset); offset++; for (int i = 0; i &lt;= anystringLength; i++) { anystring[i] = (char)EEPROM.read(offset); offset++; } // start of debug output Serial.print(&quot;any String: &quot;); Serial.println(anystring); // end of debug output </code></pre> <p><em>Note: To make things explicit, using the <code>offset</code> and incrementing it are separated. You can combine them, though. But terse code tend to be misinterpreted.</em></p> <p>This is another possible solution. Instead of expecting the length written before a string, read it until you find the end-of-string marker.</p> <p>The writing loop writes all characters including the final end-of-string marker. This works for empty strings, too.</p> <pre class="lang-cpp prettyprint-override"><code> int i; // Write anystring i = 0; do { char c = anystring[i]; EEPROM.write(offset, c); offset++; i++; } while (c != '\0'); </code></pre> <p>The reading loop does the same in the opposite direction. Using the <code>do</code>-<code>while</code> loop ensures that the end-of-string marker is read in any case.</p> <pre class="lang-cpp prettyprint-override"><code> int i; // Read anystring i = 0; do { char c = EEPROM.read(offset); anystring[i] = c; offset++; i++; } while (c != '\0'); // start of debug output Serial.print(&quot;any String: &quot;); Serial.println(anystring); // end of debug output </code></pre> <p>Like the original the solutions lack error checks, for example of too long strings, which are left as an exercise to the reader.</p> <p>Another bonus point will be received, if you extract these loops into functions. It simplifies the code and removes duplicates. [Edit] I found that the <code>EEPROM</code> class already provides <code>writeString()</code> and <code>readString()</code>. You should read its documentation and consider the usage.</p>
95398
|arduino-nano|motor|analogwrite|
Is it possible to use analogWrite() using an external Power Supply Unit?
2024-01-28T10:24:58.563
<p>As far as I know, my Arduino Nano can perform <code>analogWrite()</code> ranging from 0 to 1023 for 0 to 5 V respectively, but I want to control a DC motor which requires 9 V for good performance. Is it possible to do so?</p>
<p>Yes, that is possible.</p> <p><code>analogWrite()</code> sends out a 5 V PWM signal (3.3 V on some Arduinos) from a pin. You can't use this PWM signal to drive a motor directly; an Arduino IO pin can't deliver enough current for that.</p> <p>You will have to get a separate 9 V power supply that can supply enough current for the motor, and use a BJT or MOSFET to switch that 9 V with the PWM signal from the Arduino, or use a dedicated motor driver IC or module.</p> <p>There are plenty of schematics for this on the interwebs.</p>
95410
|esp32|sd-card|esp32-cam|esp32-s3|
Compressing grayscale image with ESP32-S3-WROOM Freenove
2024-01-30T06:12:28.530
<p>I have a ESP32-S3-WROOM module by Freenove which has a camera and a micro SD card module. I can take a snapshot as a PIXELFORMAT_JPEG photo.</p> <p>However, when I change the pixelformat to &quot;PIXELFORMAT_GRAYSCALE&quot;, the module captures the raw data (1 byte for each pixel) which is 480 kB constant for SVGA (600x800).</p> <p>How can I compress this raw data to jpg? I also tried the way of saving the photo to a &quot;.jpg&quot; file, however, it did not work.</p> <p>This is my capturing code for it:</p> <pre class="lang-cpp prettyprint-override"><code>/********************************************************************** Filename : Camera and SDcard Description : Use the onboard buttons to take photo and save them to an SD card. Auther : www.freenove.com Modification: 2022/11/02 **********************************************************************/ #include &quot;esp_camera.h&quot; #define CAMERA_MODEL_ESP32S3_EYE #include &quot;camera_pins.h&quot; #include &quot;ws2812.h&quot; #include &quot;sd_read_write.h&quot; #define BUTTON_PIN 0 void setup() { Serial.begin(500000); Serial.setDebugOutput(false); Serial.println(); pinMode(BUTTON_PIN, INPUT_PULLUP); ws2812Init(); sdmmcInit(); //removeDir(SD_MMC, &quot;/camera&quot;); createDir(SD_MMC, &quot;/camera&quot;); listDir(SD_MMC, &quot;/camera&quot;, 0); if(cameraSetup()==1){ ws2812SetColor(2); } else{ ws2812SetColor(1); return; } } void loop() { if (digitalRead(BUTTON_PIN)==LOW) { delay(20); if (digitalRead(BUTTON_PIN)==LOW) { ws2812SetColor(3); while (digitalRead(BUTTON_PIN)==LOW); camera_fb_t * fb = NULL; fb = esp_camera_fb_get(); if (fb != NULL) { int photo_index = readFileNum(SD_MMC, &quot;/camera&quot;); if (photo_index!=-1) { String path = &quot;/camera/&quot; + String(photo_index) +&quot;.jpg&quot;; Serial.println(fb-&gt;len); writejpg(SD_MMC, path.c_str(), fb-&gt;buf, fb-&gt;len); } esp_camera_fb_return(fb); } else { Serial.println(&quot;Camera capture failed.&quot;); } ws2812SetColor(2); } } } int cameraSetup(void) { camera_config_t config; config.ledc_channel = LEDC_CHANNEL_0; config.ledc_timer = LEDC_TIMER_0; config.pin_d0 = Y2_GPIO_NUM; config.pin_d1 = Y3_GPIO_NUM; config.pin_d2 = Y4_GPIO_NUM; config.pin_d3 = Y5_GPIO_NUM; config.pin_d4 = Y6_GPIO_NUM; config.pin_d5 = Y7_GPIO_NUM; config.pin_d6 = Y8_GPIO_NUM; config.pin_d7 = Y9_GPIO_NUM; config.pin_xclk = XCLK_GPIO_NUM; config.pin_pclk = PCLK_GPIO_NUM; config.pin_vsync = VSYNC_GPIO_NUM; config.pin_href = HREF_GPIO_NUM; config.pin_sscb_sda = SIOD_GPIO_NUM; config.pin_sscb_scl = SIOC_GPIO_NUM; config.pin_pwdn = PWDN_GPIO_NUM; config.pin_reset = RESET_GPIO_NUM; config.xclk_freq_hz = 20000000; config.frame_size = FRAMESIZE_SVGA; config.pixel_format = PIXFORMAT_GRAYSCALE; // for streaming config.grab_mode = CAMERA_GRAB_WHEN_EMPTY; config.fb_location = CAMERA_FB_IN_PSRAM; config.jpeg_quality = 20; config.fb_count = 1; // if PSRAM IC present, init with UXGA resolution and higher JPEG quality // for larger pre-allocated frame buffer. if (psramFound()) { config.jpeg_quality = 10; config.fb_count = 2; config.grab_mode = CAMERA_GRAB_LATEST; } else { // Limit the frame size when PSRAM is not available config.frame_size = FRAMESIZE_SVGA; config.fb_location = CAMERA_FB_IN_DRAM; } // camera init esp_err_t err = esp_camera_init(&amp;config); if (err != ESP_OK) { Serial.printf(&quot;Camera init failed with error 0x%x&quot;, err); return 0; } sensor_t * s = esp_camera_sensor_get(); // initial sensors are flipped vertically and colors are a bit saturated s-&gt;set_vflip(s, 1); // flip it back s-&gt;set_brightness(s, 1); // up the brightness just a bit s-&gt;set_saturation(s, 0); // lower the saturation Serial.println(&quot;Camera configuration complete!&quot;); return 1; } </code></pre> <p>This is the <code>writejpg()</code> function that the code snippet used:</p> <pre class="lang-cpp prettyprint-override"><code>void writejpg(fs::FS &amp;fs, const char * path, const uint8_t *buf, size_t size){ File file = fs.open(path, FILE_WRITE); if (!file) { Serial.println(&quot;Failed to open file for writing&quot;); ws2812SetColor(1); delay(100); return; } file.write(buf, size); // Define the chunk size const size_t chunkSize = 2048; // Write to serial in chunks for (size_t i = 0; i &lt; size; i += chunkSize) { // Calculate the size of the current chunk size_t currentChunkSize = ((i + chunkSize) &lt;= size) ? chunkSize : (size - i); // Write the current chunk in hex format to serial for (size_t j = 0; j &lt; currentChunkSize; ++j) { Serial.printf(&quot;%02X &quot;, buf[i + j]); // if ((j + 1) % 128 == 0) { // Print a new line every 16 bytes for better readability // Serial.println(); // } } } Serial.println(); Serial.printf(&quot;Saved file to path: %s\r\n&quot;, path); } </code></pre> <p>This function also prints out the hexadecimal values of the image for debugging.</p> <p>So, do you guys have any ideas for compressing this image into a jpg file?</p>
<p>I just managed to solve this problem with using <code>frame2jpg()</code> function.</p> <p>Hope it helps!</p>
95426
|arduino-uno|esp8266|arduino-iot-cloud|
How to connect an Arduino Uno with an ESP-01 to the Arduino IoT cloud?
2024-02-01T05:35:59.137
<p>I have been trying to connect to the Arduino IoT cloud using my Arduino Uno and an ESP-01.</p> <p>The Arduino IoT cloud does not recognize my device as genuine. Hence, I've been trying to create a <code>thing</code> and connecting it as a third-party device. I have an ESP-01 WiFi module that I want to use to connect to the IoT cloud.</p> <p>I tried the following connection:</p> <pre> Arduino ----> ESP-01 3.3V ------> 3v3 3.3V ------> EN(CH_PD) TX(1) ------> TX RX(0) ------> RX GND ------> GND </pre> <p>I also tried to reverse the connections of the RX and TX pins. Still no success. I want to connect to the cloud and use some sensors to update the cloud variables. How do I do it? Any kind of help is highly appreciated.</p> <p>Edit: I tried to upload the code that thd cloud editor provided and it throws and error saying:</p> <pre><code>fatal error: list: No such file or directory #include &lt;list&gt; </code></pre>
<p>Arduino IoT Cloud doesn't support Arduino Uno, but it does support esp8266.</p> <p>You have to do the communication with the IoT Cloud from a ESP-01 sketch with <a href="https://github.com/esp8266/Arduino?tab=readme-ov-file#installing-with-boards-manager" rel="nofollow noreferrer">esp8266 Arduino Core</a>. Then you can pass the values from/to a sketch in Uno over Serial.</p> <p>There are ESP8266 development boards which can replace the Uno in many projects. Search for &quot;Wemos D1 mini&quot; or &quot;NodeMCU&quot; ESP8266 modules.</p> <p>The ESP32 is even more capable MCU with WiFi and Arduino Core is available. It is too supported in Arduino Cloud and Arduino even has a new Nano ESP32 board.</p>
95449
|arduino-uno|led-matrix|
Why doesn't this code for an 8x8 LED matrix work properly?
2024-02-04T20:02:50.713
<p>There's an Arduino Uno (Keyestudio KS0078) and a 788BS 8x8 LED matrix. I built the circuit as on the image and ran this program:</p> <pre class="lang-cpp prettyprint-override"><code>#define MY_PERIOD 200 int displayColumn = 0; uint32_t tmr1; unsigned char Text[] = { 0x00, 0x1c, 0x22, 0x22, 0x22, 0x22, 0x22, 0x1c }; void Draw_point(unsigned char x, unsigned char y) { clear(); digitalWrite(x + 2, HIGH); digitalWrite(y + 10, LOW); delay(1); } void show_num(void) { unsigned char i, j, data; for (i = 0; i &lt; 8; i++) { data = Text[i]; data &lt;&lt;= displayColumn; for (j = 0; j &lt; 8; j++) { if (data &amp; 0x01) { Draw_point(j, i); } data &gt;&gt;= 1; } } } void setup() { Serial.begin(9600); int i = 0; for (i = 2; i &lt; 18; i++) { pinMode(i, OUTPUT); } clear(); } void loop() { show_num(); if (millis() - tmr1 &gt;= MY_PERIOD) { tmr1 = millis(); displayColumn++; if (displayColumn &gt; 7) { displayColumn = 0; } } } void clear() { for (int i = 2; i &lt; 10; i++) digitalWrite(i, LOW); for (int i = 10; i &lt; 18; i++) digitalWrite(i, HIGH); } </code></pre> <p><a href="https://i.stack.imgur.com/BUZAz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BUZAz.png" alt="circuit" /></a></p> <p>I got the code from the <a href="https://wiki.keyestudio.com/KS0077%2878,79%EF%BC%89Super_Learning_Kit_for_Arduino#Project_19:_8*8_LED_Matrix" rel="nofollow noreferrer">Keyestudio examples wiki</a> and added a part with <code>displayColumn</code> and shifting to the left every 0.2 sec. But instead of fading out fully on the 7th step, one LED (x=0, y=6) stays on. Even if I stop executing <code>show_num</code> when <code>displayColumn &gt; 7</code> it stays on as long as there is power. Why?</p> <p>UPD: I removed dynamic shifting in <code>loop</code> and set <code>displayColumn</code> in 5, 6 and 7 - the display showed correct result and was empty when <code>displayColumn</code> was equal to 7. Obviously the bug hides between &quot;transitions&quot;.</p> <p>UPD2: If I try the programm with other symbol, the bug on the step 7 always repeats with other LED which was the last lighted one on the step 6.</p> <p>UPD3: Debug data by request of @thebusybee (repeated blocks removed)</p> <pre><code>x,y:2,1 x,y:3,1 x,y:4,1 x,y:1,2 x,y:5,2 x,y:1,3 x,y:5,3 x,y:1,4 x,y:5,4 x,y:1,5 x,y:5,5 x,y:1,6 x,y:5,6 x,y:2,7 x,y:3,7 x,y:4,7 displayColumn: 1 x,y:3,1 x,y:4,1 x,y:5,1 x,y:2,2 x,y:6,2 x,y:2,3 x,y:6,3 x,y:2,4 x,y:6,4 x,y:2,5 x,y:6,5 x,y:2,6 x,y:6,6 x,y:3,7 x,y:4,7 x,y:5,7 displayColumn: 2 x,y:4,1 x,y:5,1 x,y:6,1 x,y:3,2 x,y:7,2 x,y:3,3 x,y:7,3 x,y:3,4 x,y:7,4 x,y:3,5 x,y:7,5 x,y:3,6 x,y:7,6 x,y:4,7 x,y:5,7 x,y:6,7 displayColumn: 3 x,y:5,1 x,y:6,1 x,y:7,1 x,y:4,2 x,y:4,3 x,y:4,4 x,y:4,5 x,y:4,6 x,y:5,7 x,y:6,7 x,y:7,7 displayColumn: 4 x,y:6,1 x,y:7,1 x,y:5,2 x,y:5,3 x,y:5,4 x,y:5,5 x,y:5,6 x,y:6,7 x,y:7,7 displayColumn: 5 x,y:7,1 x,y:6,2 x,y:6,3 x,y:6,4 x,y:6,5 x,y:6,6 x,y:7,7 displayColumn: 6 x,y:7,2 x,y:7,3 x,y:7,4 x,y:7,5 x,y:7,6 displayColumn: 7 //many many empty strings displayColumn: 8 </code></pre> <p><a href="https://i.stack.imgur.com/xpv7E.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xpv7E.jpg" alt="enter image description here" /></a></p>
<p>As an addition to your answer, this is for future visitors who want to learn more.</p> <h4>1. Programming by Accident</h4> <p>Your analysis is correct, mine in an early comment is wrong.</p> <p>The last LED of the second last &quot;picture&quot; is not cleared when the last &quot;picture&quot; is drawn. This is because you clear the matrix <strong>only, if you switch on an LED.</strong></p> <p>This is your original code:</p> <pre class="lang-cpp prettyprint-override"><code>void Draw_point(unsigned char x, unsigned char y) { clear(); digitalWrite(x + 2, HIGH); digitalWrite(y + 10, LOW); delay(1); } </code></pre> <p>In your solution you clear the complete matrix after the delay, which results in the expected effect.</p> <p>However, you did not analyze the underlying to the end. You changed something after a random suggestion, and it &quot;works.&quot; I have seen this so many times.</p> <p>We know that <code>Draw_point()</code> handles only <strong>one</strong> LED. So we do not need to reset <strong>all</strong> pins to their respective off levels, 14 of the 16 are already fine. It suffices to do this for the single LED just switched on.</p> <pre class="lang-cpp prettyprint-override"><code>void Draw_point(unsigned char x, unsigned char y) { digitalWrite(x + 2, HIGH); digitalWrite(y + 10, LOW); delay(1); digitalWrite(x + 2, LOW); digitalWrite(y + 10, HIGH); } </code></pre> <h4>2. Driving the LEDs in Reverse</h4> <p>As I mentioned in a comment, you drive the LEDs of the matrix in reverse, when they are off. We all know that comments will not be read, mostly. So I add this here. ;-)</p> <p>Most LEDs stand some voltage in reverse. According to the <a href="http://www.ledtoplite.com/uploadfile/2014/0807/20140807032939345.pdf" rel="nofollow noreferrer">788BS' data sheet</a> it has 5V as <strong>absolute maximum</strong> rating. I would not dare to apply that really.</p> <p>All professionals drive their LED matrices such that only forward current is applied. All other LEDs are not driven at all.</p> <p>The solution here is to change the pin mode of the pins.</p> <pre class="lang-cpp prettyprint-override"><code>#define MY_PERIOD 200 int displayColumn = 0; uint32_t tmr1; unsigned char Text[] = { 0x00, 0x1c, 0x22, 0x22, 0x22, 0x22, 0x22, 0x1c }; void Draw_point(unsigned char x, unsigned char y) { pinMode(x + 2, OUTPUT); digitalWrite(x + 2, HIGH); pinMode(y + 10, OUTPUT); digitalWrite(y + 10, LOW); delay(1); pinMode(x + 2, INPUT); pinMode(y + 10, INPUT); } void show_num(void) { unsigned char i, j, data; for (i = 0; i &lt; 8; i++) { data = Text[i]; data &lt;&lt;= displayColumn; for (j = 0; j &lt; 8; j++) { if (data &amp; 0x01) { Draw_point(j, i); } data &gt;&gt;= 1; } } } void setup() { } void loop() { show_num(); if (millis() - tmr1 &gt;= MY_PERIOD) { tmr1 = millis(); displayColumn++; if (displayColumn &gt; 7) { displayColumn = 0; } } } </code></pre> <p>You don't need to <code>clear()</code> in <code>setup()</code>, because all pins are initially in &quot;input&quot; mode already.</p> <h4>3. About Flicker</h4> <p>You tried with no <code>delay()</code> and see only a dim display. This is correct as the time the LED is on is short compared to the time of the rest of the program.</p> <p>With <code>delay(2)</code> you experience flicker. Let's think about the timing here.</p> <p>There are different &quot;pictures&quot; during the scroll, with the listed number of LEDs switch on:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th><code>displayColumn</code></th> <th>Number of LEDs switched on</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>16</td> </tr> <tr> <td>1</td> <td>16</td> </tr> <tr> <td>2</td> <td>16</td> </tr> <tr> <td>3</td> <td>11</td> </tr> <tr> <td>4</td> <td>9</td> </tr> <tr> <td>5</td> <td>7</td> </tr> <tr> <td>6</td> <td>5</td> </tr> <tr> <td>7</td> <td>0</td> </tr> </tbody> </table></div> <p>Because the Arduino is quite fast, we came approximate the calculations by neglecting the rest of the program.</p> <p>Each single LED is shown for 2 ms according to <code>delay(2)</code>, so a complete picture sums up to repetition periods between (nearly) 0 ms (<code>displayColumn</code> = 7) and 32 ms (<code>displayColumn</code> = 0 to 2). The reciprocal gives us the display frequency, many know the term &quot;frames per second&quot; or frame rate. The lowest frame rate is with the longest period: 1 / 0.032 s = 31.25 Hz. Our eyes see this as flickering. BTW, as soon as the &quot;picture&quot; has fewer LEDs, the display will stop flickering.</p> <p>Commonly human eyes see no flicker if the frame rate exceeds about 50 to 60 Hz. With <code>delay(1)</code> the periods are only half as long as with <code>delay(2)</code>, of course. The lowest frame rate is therefore 62.5 Hz, good enough for no flicker experience.</p> <p>Please be aware that the frame rate drops with the number of LEDs switched on. If you want to have at least 50 Hz with <code>delay(1)</code>, you cannot have more than 20 LEDs: 1 / 50 Hz = 20 ms, which corresponds to 20 LEDs.</p> <p>The solution here is to show a complete row at the same time. Because then there are just 8 rows to sequence, you can raise to <code>delay(2)</code> again: 8 rows * 2 ms &lt; 20 ms. The specific code is left as an exercise to the reader. Please be aware that you need to take electrical maximum ratings into account. The MCU of the Arduino has limits to the sourced current.</p> <h4>4. Final Note</h4> <p>You might wonder why the linked resource (the Keyestudio examples wiki) shows this &quot;not-so-perfect&quot; source code. Well, as we can see from the bad formatting of the example, it was hacked down in a hurry and without being aware that beginners will be misguided.</p> <p>Take all such resources with a lot of caution. Unfortunately, this is absolutely necessary. <em>(This includes my answer here, too.)</em></p>
95456
|imu|arduino-nano-rp2040|
Machine learning on Arduino Nano RP2040
2024-02-05T12:38:46.567
<p>I am trying to use the Arduino Nano RP2040 to recognize gestures using an IMU. This board has the possibility of machine learning core features provided by the LSM6DSOX.</p> <p>I tested the <a href="https://docs.arduino.cc/tutorials/nano-rp2040-connect/rp2040-imu-advanced/" rel="nofollow noreferrer">example</a> provided by the manufacturer and everything works fine. I now want to create a new ML model to recognize custom gestures.</p> <p>I found this <a href="https://youtu.be/hHVsLHqIN9g?si=6E_qJz9t5Eonp_Ns&amp;t=348" rel="nofollow noreferrer">STM tutorial</a>, which is very helpful, but I can't find the code presented at 5:48, to record the movements.</p> <p>Does anyone know where I can find all the code or how I should do it?</p>
<p>I answer the question myself, for those who have the same problem as me.</p> <p><a href="https://github.com/arduino/ArduinoCore-mbed/blob/main/libraries/MLC/examples/RP2040_DataLogger_FIFO/RP2040_DataLogger_FIFO.ino" rel="nofollow noreferrer">Source code</a></p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;PluggableUSBMSD.h&quot; #include &quot;FlashIAPBlockDevice.h&quot; #include &quot;WiFiNINA.h&quot; #include &quot;LSM6DSOXSensor.h&quot; #define INT_1 INT_IMU #define SENSOR_ODR 104.0f // In Hertz #define ACC_FS 2 // In g #define GYR_FS 2000 // In dps #define MEASUREMENT_TIME_INTERVAL (1000.0f/SENSOR_ODR) // In ms #define FIFO_SAMPLE_THRESHOLD 199 #define FLASH_BUFF_LEN 8192 typedef enum { DATA_STORAGE_STATE, DATA_LOGGER_IDLE_STATE, DATA_LOGGER_RUNNING_STATE } demo_state_e; volatile demo_state_e demo_state = DATA_STORAGE_STATE; volatile int mems_event = 0; uint32_t file_count = 0; unsigned long timestamp_count = 0; bool acc_available = false; bool gyr_available = false; int32_t acc_value[3]; int32_t gyr_value[3]; char buff[FLASH_BUFF_LEN]; uint32_t pos = 0; static FlashIAPBlockDevice bd(XIP_BASE + 0x100000, 0x100000); LSM6DSOXSensor AccGyr(&amp;Wire, LSM6DSOX_I2C_ADD_L); USBMSD MassStorage(&amp;bd); rtos::Thread acquisition_th; FILE *f = nullptr; void INT1Event_cb() { mems_event = 1; } void USBMSD::begin() { int err = getFileSystem().mount(&amp;bd); if (err) { err = getFileSystem().reformat(&amp;bd); } } mbed::FATFileSystem &amp;USBMSD::getFileSystem() { static mbed::FATFileSystem fs(&quot;fs&quot;); return fs; } void led_green_thd() { while (1) { if (demo_state == DATA_LOGGER_RUNNING_STATE) { digitalWrite(LEDG, HIGH); delay(100); digitalWrite(LEDG, LOW); delay(100); } } } void Read_FIFO_Data(uint16_t samples_to_read) { uint16_t i; for (i = 0; i &lt; samples_to_read; i++) { uint8_t tag; // Check the FIFO tag AccGyr.Get_FIFO_Tag(&amp;tag); switch (tag) { // If we have a gyro tag, read the gyro data case LSM6DSOX_GYRO_NC_TAG: { AccGyr.Get_FIFO_G_Axes(gyr_value); gyr_available = true; break; } // If we have an acc tag, read the acc data case LSM6DSOX_XL_NC_TAG: { AccGyr.Get_FIFO_X_Axes(acc_value); acc_available = true; break; } // We can discard other tags default: { break; } } // If we have the measurements of both acc and gyro, we can store them with timestamp if (acc_available &amp;&amp; gyr_available) { int num_bytes; num_bytes = snprintf(&amp;buff[pos], (FLASH_BUFF_LEN - pos), &quot;%lu %d %d %d %d %d %d\n&quot;, (unsigned long)((float)timestamp_count * MEASUREMENT_TIME_INTERVAL), (int)acc_value[0], (int)acc_value[1], (int)acc_value[2], (int)gyr_value[0], (int)gyr_value[1], (int)gyr_value[2]); pos += num_bytes; timestamp_count++; acc_available = false; gyr_available = false; } } // We can add the termination character to the string, so we are ready to save it in flash buff[pos] = '\0'; pos = 0; } void setup() { Serial.begin(115200); MassStorage.begin(); pinMode(LEDB, OUTPUT); pinMode(LEDG, OUTPUT); digitalWrite(LEDB, LOW); digitalWrite(LEDG, LOW); // Initialize I2C bus. Wire.begin(); Wire.setClock(400000); //Interrupts. attachInterrupt(INT_1, INT1Event_cb, RISING); // Initialize IMU. AccGyr.begin(); AccGyr.Enable_X(); AccGyr.Enable_G(); // Configure ODR and FS of the acc and gyro AccGyr.Set_X_ODR(SENSOR_ODR); AccGyr.Set_X_FS(ACC_FS); AccGyr.Set_G_ODR(SENSOR_ODR); AccGyr.Set_G_FS(GYR_FS); // Enable the Double Tap event AccGyr.Enable_Double_Tap_Detection(LSM6DSOX_INT1_PIN); // Configure FIFO BDR for acc and gyro AccGyr.Set_FIFO_X_BDR(SENSOR_ODR); AccGyr.Set_FIFO_G_BDR(SENSOR_ODR); // Start Led blinking thread acquisition_th.start(led_green_thd); } void loop() { if (mems_event) { mems_event = 0; LSM6DSOX_Event_Status_t status; AccGyr.Get_X_Event_Status(&amp;status); if (status.DoubleTapStatus) { switch (demo_state) { case DATA_STORAGE_STATE: { // Go to DATA_LOGGER_IDLE_STATE state demo_state = DATA_LOGGER_IDLE_STATE; digitalWrite(LEDG, HIGH); Serial.println(&quot;From DATA_STORAGE_STATE To DATA_LOGGER_IDLE_STATE&quot;); break; } case DATA_LOGGER_IDLE_STATE: { char filename[32]; // Go to DATA_LOGGER_RUNNING_STATE state snprintf(filename, 32, &quot;/fs/data_%lu.txt&quot;, file_count); Serial.print(&quot;Start writing file &quot;); Serial.println(filename); // open a file to write some data // w+ means overwrite, so every time the board is rebooted the file will be overwritten f = fopen(filename, &quot;w+&quot;); if (f != nullptr) { // write header fprintf(f, &quot;Timestamp[ms] A_X [mg] A_Y [mg] A_Z [mg] G_X [mdps] G_Y [mdps] G_Z [mdps]\n&quot;); fflush(f); Serial.println(&quot;From DATA_LOGGER_IDLE_STATE To DATA_LOGGER_RUNNING_STATE&quot;); demo_state = DATA_LOGGER_RUNNING_STATE; digitalWrite(LEDG, LOW); timestamp_count = 0; pos = 0; acc_available = false; gyr_available = false; // Set FIFO in Continuous mode AccGyr.Set_FIFO_Mode(LSM6DSOX_STREAM_MODE); } break; } case DATA_LOGGER_RUNNING_STATE: { // Empty the FIFO uint16_t fifo_samples; AccGyr.Get_FIFO_Num_Samples(&amp;fifo_samples); Read_FIFO_Data(fifo_samples); // Store the string in flash fprintf(f, &quot;%s&quot;, buff); fflush(f); // Close the log file and increase the counter fclose(f); file_count++; // Set FIFO in Bypass mode AccGyr.Set_FIFO_Mode(LSM6DSOX_BYPASS_MODE); // Go to DATA_LOGGER_IDLE_STATE state demo_state = DATA_LOGGER_IDLE_STATE; // Wait for the led thread ends the blinking delay(250); digitalWrite(LEDG, HIGH); Serial.println(&quot;From DATA_LOGGER_RUNNING_STATE To DATA_LOGGER_IDLE_STATE&quot;); break; } default: Serial.println(&quot;Error! Invalid state&quot;); } } } if (demo_state == DATA_LOGGER_RUNNING_STATE) { uint16_t fifo_samples; // Check the number of samples inside FIFO AccGyr.Get_FIFO_Num_Samples(&amp;fifo_samples); // If we reach the threshold we can empty the FIFO if (fifo_samples &gt; FIFO_SAMPLE_THRESHOLD) { // Empty the FIFO Read_FIFO_Data(fifo_samples); // Store the string in flash fprintf(f, &quot;%s&quot;, buff); fflush(f); } } if (demo_state == DATA_STORAGE_STATE &amp;&amp; millis() &gt; 10000) { // Disable the sensor and go to Mass Storage mode AccGyr.Disable_Double_Tap_Detection(); AccGyr.Disable_X(); AccGyr.Disable_G(); while (1) { digitalWrite(LEDB, HIGH); delay(100); digitalWrite(LEDB, LOW); delay(100); } } } </code></pre>
95480
|arduino-nano|h-bridge|l293d|
Arduino works indefinitely without PC contact
2024-02-08T11:22:09.047
<p>I'm studying H-Bridge for DC motors. I have a 9V battery, DC motor (9v), Arduino Nano and L293D. I'm following Jeremy Bloom's book about Arduino. Well, the system works perfectly with a PC connected. When I turn off the PC and connect the battery only, it doesn't work at all. The system should work only with a 9V battery.</p> <pre><code>const uint8_t MC1 = 8; const uint8_t MC2 = 7; const uint8_t POT = 0; uint16_t velocity = 0; uint16_t PWM = 0; void forward(uint16_t); void reverse(uint16_t); void brake(); void setup(){ Serial.begin(9600); pinMode(EN, OUTPUT); pinMode(MC1, OUTPUT); pinMode(MC2, OUTPUT); brake(); } void loop(){ Serial.println(PWM); PWM = analogRead(POT); if (PWM &gt; 562){ velocity = map(PWM, 563, 1023, 0, 255); forward(velocity); } if (PWM &lt; 462){ velocity = map(PWM, 461, 0, 0, 255); reverse(velocity); } } void forward(uint16_t speedValue){ digitalWrite(EN, LOW); digitalWrite(MC1, HIGH); digitalWrite(MC2, LOW); analogWrite(EN, speedValue); } void reverse(uint16_t speedValue){ digitalWrite(EN, LOW); digitalWrite(MC1, LOW); digitalWrite(MC2, HIGH); analogWrite(EN, speedValue); } void brake(){ digitalWrite(EN, LOW); digitalWrite(MC1, LOW); digitalWrite(MC2, LOW); digitalWrite(EN, HIGH); }``` The A0 pin is used to rotate the sensor (PWM). [![The circuit][1]][1] [1]: https://i.stack.imgur.com/GliSw.png </code></pre>
<blockquote> <p>Well, I connected 7.4V 1500mAh Li-ion battery and... it's working. Could you explain why??</p> </blockquote> <p>The PP3 batteries (rectangular 9v battery with snap-on terminals) can supply only a very limited amount of current; barely enough to run an Arduino at all, and none left over to run a motor or other higher current devices.<br> The best application for PP3s is in low-current, standby devices like smoke detectors, which need very little current under normal circumstances (no smoke) but can draw enough current to make a lot of noise for long enough to wake you up and alert you to the danger, when they detect smoke.</p> <p>For your application you need a larger capacity battery that can supply more current. Carbon, Alkaline, and nickel chemistries could all work, provided the battery is large enough to supply the current you need; the PP3's form factor is its limitation. Li-ion's big advantage over the other chemistries is, of course, it's rechargeability, and with less degradation than Nickel-based rechargeables.</p>
95499
|serial|
Multiple symbol definition related to USART_RX_vect from Serial
2024-02-10T21:54:17.770
<p>When trying to compile the sketch below, I get this error when using either the IDE or the CLI:</p> <pre><code>HardwareSerial0.cpp.o (symbol from plugin): In function `Serial': (.text+0x0): multiple definition of `__vector_18' </code></pre> <p>This seems to have something to do with multiple definitions of <code>USART_RX_vect</code>.</p> <p>Since I'm not using any extra libraries, that doesn't seem to be the source of the problem (though library conflicts are the source of many similar problems I've seen on here and elsewhere). Any suggestions on how to fix this?</p> <p>Sketch:</p> <pre class="lang-cpp prettyprint-override"><code>// Listen to the Serial Port for Instructions and Print Register Values volatile boolean start = false; // flag to start register inspection; global void setup() { Serial.begin(9600); if (Serial) { Serial.println(&quot;Arduino listening...&quot;); Serial.println(&quot;Enter g or s at any time&quot;); // g = go, s = stop } } void loop() { while (start) { // print the values of some ADC registers Serial.print(&quot;ADMUX register: &quot;); print_bin(ADMUX); Serial.print(&quot;ADCSRA register: &quot;); print_bin(ADCSRA); Serial.println(&quot; &quot;); delay(1000); } } ISR(USART_RX_vect) { unsigned char data; data = UDR0; if (data == 'g') { start = true; } if (data == 's') { start = false; } } void print_bin(byte aByte) { for (int8_t aBit = 7; aBit &gt;= 0; aBit--) { if (aBit == 3) { Serial.print(&quot; &quot;); } Serial.print(bitRead(aByte, aBit) ? '1' : '0'); } Serial.println(&quot; &quot;); } </code></pre> <p>Using the Arduino IDE as follows:<br /> Version: 2.3.0<br /> Date: 2024-02-07T13:40:21.377Z<br /> CLI Version: 0.35.2</p>
<p><code>USART_RX_vect</code> is defined by the Arduino core library. It is part of the implementation of the <code>Serial</code> object. Your sketch has a second definition of the same ISR, thus the conflict.</p> <p>Basically you have two choices: either you write your own code to handle the serial port at the I/O register level (like in your ISR above), or you rely on the <code>Serial</code> implementation of the Arduino core (<code>Serial.available()</code> and <code>Serial.read()</code> to read data). You cannot mix the approaches like you are trying to do here.</p>
95504
|arduino-uno|serial|
Can't get serial port's attention once sketch is running
2024-02-11T23:28:01.777
<p>This sketch is supposed to listen for a single character sent to the serial port, as a means of starting and stopping data collection (which in this example is mocked by printing some register values). It reacts to the first character sent (<code>g</code>), and the <code>while</code> loop begins executing. But it doesn't react to a subsequent <code>s</code> character, it seems I can't get Arduino's attention.</p> <p>Perhaps this is related to this <a href="https://arduino.stackexchange.com/a/72312/93110">answer</a> but I'm not sure. If that's the problem, I could use some general suggestions about how to work around the limitations. If it's something else, well obviously I need a suggestion for that as well!</p> <pre><code>// Listen to the Serial Port for Instructions and Print Register Values volatile boolean start = false; // flag to start register inspection; global void setup() { Serial.begin(9600); if (Serial) { Serial.println(&quot;Arduino listening...&quot;); Serial.println(&quot;Enter g or s at any time&quot;); // g = go, s = stop } } void loop() { unsigned char data; if (Serial.available()) { data = Serial.read(); Serial.println(data); // only for troubleshooting if (data == 'g') { start = true; } else if (data == 's') { start = false; } } while (start) { // print the values of some ADC registers Serial.print(&quot;ADMUX register: &quot;); print_bin(ADMUX); Serial.print(&quot;ADCSRA register: &quot;); print_bin(ADCSRA); Serial.println(&quot; &quot;); delay(1000); } } void print_bin(byte aByte) { for (int8_t aBit = 7; aBit &gt;= 0; aBit--) { if (aBit == 3) { Serial.print(&quot; &quot;); } Serial.print(bitRead(aByte, aBit) ? '1' : '0'); } Serial.println(&quot; &quot;); } </code></pre> <p>Environment: Version: 2.3.0 Date: 2024-02-07T13:40:21.377Z CLI Version: 0.35.2</p>
<p>There is nothing in your <code>while (start) {</code> loop that would allow <code>start</code> to become <code>false</code>.</p> <pre class="lang-cpp prettyprint-override"><code> while (start) { // print the values of some ADC registers Serial.print(&quot;ADMUX register: &quot;); print_bin(ADMUX); Serial.print(&quot;ADCSRA register: &quot;); print_bin(ADCSRA); Serial.println(&quot; &quot;); delay(1000); } </code></pre> <p>...and so your loop continues while data is piling up in <code>Serial</code>'s input buffer.</p> <p><code>loop()</code> is already a functional loop. Changing <code>while (start) {</code> to <code>if (start) {</code> seems to be what you're looking for.</p> <pre class="lang-cpp prettyprint-override"><code>void loop() { // &lt;-- existing loop unsigned char data; if (Serial.available()) { // stuff that can change start } if (start) { // stuff that happens if start is true } } </code></pre> <p>You may want to look at the <a href="https://docs.arduino.cc/built-in-examples/digital/BlinkWithoutDelay/" rel="nofollow noreferrer">blink without delay example</a> for handling your <code>delay(1000)</code> differently.</p>
95525
|esp32|mpu6050|accelerometer|gyroscope|
Difficulties acquiring angle values from MPU6050
2024-02-14T19:21:44.007
<p>I'm attempting to acquire angle values from an <a href="https://components101.com/sites/default/files/component_datasheet/MPU6050-DataSheet.pdf" rel="nofollow noreferrer">MPU6050</a> IMU sensor using an <a href="https://docs.espressif.com/projects/esp-idf/en/stable/esp32/hw-reference/esp32/user-guide-devkitm-1.html" rel="nofollow noreferrer">ESP32-DevKitM-1</a> microcontroller.</p> <p>My setup contains the ESP32 board, the MPU6050 board, and an SD card reader to save the readings from the sensor:</p> <p><a href="https://i.stack.imgur.com/7dkqvm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7dkqvm.jpg" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/F55y6m.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F55y6m.jpg" alt="enter image description here" /></a></p> <p>I'm using the Arduino IDE v2.3.0.</p> <p>I adapted the following testing code excerpt from <a href="https://electronics.stackexchange.com/questions/142037/calculating-angles-from-mpu6050">another post about sensor</a>, using the newer Adafruit_MPU6050 library and the SD functions:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;Wire.h&gt; #include &quot;SPI.h&quot; #include &lt;Adafruit_Sensor.h&gt; #include &lt;Adafruit_MPU6050.h&gt; #include &quot;SD.h&quot; const int PIN_IMU_SCL = 22; const int PIN_IMU_SDA = 21; const int PIN_SD_CS = 23; const int PIN_SD_MISO = 10; const int PIN_SD_MOSI = 18; const int PIN_SD_CLK = 5; const int IMU_GyroScale = 131; Adafruit_MPU6050 IMU; double IMU_Time; double IMU_TimePrev = -1; double IMU_GyroRotX; double IMU_GyroRotY; double IMU_GyroRotZ; File DataFile; void IMU_GetData(double&amp; angleX, double&amp; angleY, double&amp; angleZ, double&amp; temp) { bool firstTime = false; if (IMU_TimePrev == -1) firstTime = true; // Calculating the elapsed time... IMU_TimePrev = IMU_Time; IMU_Time = millis(); double timeDelta = (IMU_Time - IMU_TimePrev) / 1000; // Acquiring the readings from the accelerometer &amp; gyroscope... sensors_event_t accelData; sensors_event_t gyroData; sensors_event_t tempData; IMU.getEvent(&amp;accelData, &amp;gyroData, &amp;tempData); // Calculating the accelerometer angle... double accelRotX = (180 / PI) * atan(accelData.acceleration.x / sqrt(pow(accelData.acceleration.y, 2) + pow(accelData.acceleration.z, 2))); double accelRotY = (180 / PI) * atan(accelData.acceleration.y / sqrt(pow(accelData.acceleration.x, 2) + pow(accelData.acceleration.z, 2))); double accelRotZ = (180 / PI) * atan(sqrt(pow(accelData.acceleration.x, 2) + pow(accelData.acceleration.y, 2)) / accelData.acceleration.z); // Calculating the gyroscope angle... double gyroRotX = (gyroData.gyro.x / IMU_GyroScale); double gyroRotY = (gyroData.gyro.y / IMU_GyroScale); double gyroRotZ = (gyroData.gyro.z / IMU_GyroScale); // Combining the two (complementary filter)... if (firstTime) { IMU_GyroRotX = accelRotX; IMU_GyroRotY = accelRotY; IMU_GyroRotZ = accelRotZ; } else { IMU_GyroRotX += timeDelta * gyroRotX; IMU_GyroRotY += timeDelta * gyroRotY; IMU_GyroRotZ += timeDelta * gyroRotZ; } angleX = (0.96 * accelRotX) + (0.04 * IMU_GyroRotX); angleY = (0.96 * accelRotY) + (0.04 * IMU_GyroRotY); angleZ = (0.96 * accelRotZ) + (0.04 * IMU_GyroRotZ); temp = tempData.temperature; } bool IMU_Init() { bool status = IMU.begin(); if (status) { IMU.setAccelerometerRange(MPU6050_RANGE_8_G); IMU.setGyroRange(MPU6050_RANGE_500_DEG); IMU.setFilterBandwidth(MPU6050_BAND_21_HZ); } IMU_Time = millis(); delay(100); return status; } void setup() { Serial.begin(9600); Serial.println(&quot;Initializing...&quot;); Wire.begin(PIN_IMU_SDA, PIN_IMU_SCL); IMU_Init(); SPI.begin(PIN_SD_CLK, PIN_SD_MISO, PIN_SD_MOSI, PIN_SD_CS); while (!SD.begin(PIN_SD_CS)) { Serial.println(&quot;Unable to open SD!&quot;); delay(500); } DataFile = SD.open(&quot;/angles.txt&quot;, FILE_WRITE); DataFile.close(); delay(100); Serial.println(&quot;Initialized!&quot;); } void loop() { double angleX; double angleY; double angleZ; double temp; IMU_GetData(angleX, angleY, angleZ, temp); String anglesStr = String(angleX) + &quot;:&quot; + String(angleY) + &quot;:&quot; + String(angleZ); DataFile = SD.open(&quot;/angles.txt&quot;, FILE_APPEND); DataFile.println(anglesStr); DataFile.close(); Serial.println(anglesStr); delay(200); } </code></pre> <p>Where <code>IMU_GetData</code> is the function responsible for acquiring the angle data from the gyroscope and the accelerator sensors on the MPU6050 board, and implementing a filter to attain a set of filtered angle values.</p> <p>I then simply save the filtered angle values to the SD card. I communicate with the sensor using the Wire I2C library, and with the SD card using the SPI library.</p> <p>The main issue I'm running into is the fact that the resultant angle values do not appear to accurately represent the rotation of the sensor.</p> <p>As a test, I rotated the sensor 360° slowly around each one of the 3 axes, and saved the continuous angle readings during each rotation:</p> <p><a href="https://i.stack.imgur.com/ctcPEm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ctcPEm.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/tWnvwm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tWnvwm.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/V9Uwem.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V9Uwem.png" alt="enter image description here" /></a></p> <p>The time interval between each reading in the plots above is ~0.2 s.</p> <p>The first issue is that a rotation about the Z-axis visible in the last graph above appears to not cause any appreciable change in any of the angle readings.</p> <p>I initally assumed that could be caused by the value of the <code>IMU_GyroScale</code> constant that the gyroscope angle values get multiplied by during the calculations carried out in the <code>IMU_GetData</code> function. I assumed that all MPU6050 chips will use that same scaling factor, but then I tried several of the other listed scaling factors listed in the datasheet, with no appreciable difference.</p> <p>Is there something visibly wrong in my code with the angle calculations for the Z-axis? Could this be a sign of a defective sensor board?</p> <p>The second thing I was curious about was the format of the filtered angle values.</p> <p>I initially assumed that the filtered angle values I would be getting from the sensor would be the Euler angles; Roll, Pitch &amp; Yaw. However, these appear to not represent those.</p> <p>In fact, <a href="https://www.geekmomprojects.com/gyroscopes-and-accelerometers-on-a-chip/" rel="nofollow noreferrer">one of the main sources listed in the original posting</a> that describes in detail the process of calculating the filtered angle values, also provides a visualization of the angle values acquired from the sensor:</p> <p><a href="https://i.stack.imgur.com/5uY5Nm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5uY5Nm.jpg" alt="enter image description here" /></a></p> <p>Are these &quot;tilt&quot; values related to Euler angles? Is it possible to convert between the two?</p>
<p>The formulas you are using look plain wrong. There are a few issues that stick out:</p> <ul> <li><p>Rotating along <em>z</em> has no effect on the accelerometers. Any formula that pretends to give you the three Euler angles out of accelerometer data can only be wrong. You need a magnetic compass to get the yaw angle, otherwise you would have to rely solely on the gyros, which are prone to long-term drift.</p> </li> <li><p>The formulas for updating angles from gyro data are awfully complex. You don't want to do that. You want to instead keep track of you attitude using quaternions, which give much nicer maths.</p> </li> <li><p>If you look at the formulas that update <code>IMU_GyroRot*</code>, you should notice that they are prone to unbounded drift, which is then inherited by <code>angle*</code>. Obviously, the author of these formulas completely missed the point of a complementary filter.</p> </li> </ul> <p>I suggest you look at <a href="https://arduino.stackexchange.com/a/88413/7508">this old answer</a> to a very similar question.</p>
95531
|serial|esp8266|button|pull-up|pinmode|
Sketch halts if button is pressed on boot
2024-02-15T10:09:33.497
<p>I have a KY-040 rotary encoder with a push button wired to an ESP8266. My objective is to be able to detect if the button is pressed or not on boot.</p> <p>In the below code, if I hold the button down and power on the ESP8266, neither &quot;IT'S STARTED&quot; or &quot;IT'S LOOPING&quot; is printed in the serial monitor, even if I release the button. If I don't press the button, the code works as expected and prints &quot;IT'S STARTED&quot; followed by &quot;IT'S LOOPING&quot;. It's as though the code gets stuck/halted if I press the button on boot.</p> <p>Can someone explain why this is happening?</p> <p>I would also appreciate suggestions on how I can detect the status (pressed/not pressed) of the button when the ESP8266 is powered up.</p> <p>Here is my code:</p> <pre class="lang-cpp prettyprint-override"><code>void setup() { pinMode(D3, INPUT_PULLUP); Serial.begin(115200); Serial.println(&quot;IT'S STARTED&quot;); } void loop() { Serial.println(&quot;IT'S LOOPING&quot;); delay(1000); } </code></pre>
<p>Description of pin D3 from <a href="https://randomnerdtutorials.com/esp8266-pinout-reference-gpios/" rel="nofollow noreferrer">this ESP8266 pinout reference</a>:</p> <blockquote> <p>connected to FLASH button, boot fails if pulled LOW</p> </blockquote> <p>So you cannot pull this pin to LOW during boot, as it will keep the ESP in flash mode. You need to use a pin, that doesn't have this limitation, like D1, D2, D5, D6 or D7.</p>
95533
|esp8266|atmega328|pins|
Physically passing through a pin to access another
2024-02-15T10:42:03.143
<p>I would like to know about physically passing through a pin in order to get to another. For instance, if I have a sensor on one side of an ATMEGA328P or ESP8266 (Wemos D1 Mini) yet need to connect to a pin on the other side, would I be able to simply go through an unused pin instead of worrying about going around or using a jumper wire? If so, would I need to set the unused pin in a certain way, for example as an input (with or without pull-up)?</p> <p>PS: The diagram of the first answer illustrates my question exactly and the answer has been accepted as the solution.</p>
<p>Make sure that the unused pin isn't configured for any conflicting functions like SPI, I2C, or UART communication, as this could interfere with the signal you're routing.</p>
95535
|power|code-review|rtc|oled|seeeduino-xiao|
Code review for timer using RTC and OLED screen
2024-02-15T16:12:55.060
<p>I am building a small art project to display my current age with an accuracy of 1/100th of a second. I am using a XIAO SAMD21, a DS3231 RTC, and a 128x32 OLED screen. Here is what it looks like right now without the battery:</p> <p><a href="https://i.stack.imgur.com/i1Kyw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i1Kyw.png" alt="enter image description here" /></a></p> <p>My aim is to fit this and a battery into a locket / necklace. I want to make as low-power as possible so that it can last at least an hour or two on a 75 mAh Li-po. I can't use a bigger battery since it wouldn't fit in the necklace.</p> <p>I wrote the code to the best of my ability and it looks like it works really well. I just want a sanity check to make sure there isn't a simpler way of doing things. In particular I feel like the calculation of the age in the main loop, the syncing with RTC, and maybe the display updates, could be done in a better way. Maybe there are some things I do with interrupts and the 'alarms' in the RTC? Just power on the display every other second maybe. I am also considering using an epaper display and removing the power LED.</p> <p>The code is attached here. I use the Adafruit libraries to drive the SSD1306 on the OLED screen, and one of the DS3231 libraries to interface with the RTC. Parts of it are adapted from examples, so there may be some extraneous imports or declarations I don't need.</p> <pre class="lang-cpp prettyprint-override"><code>// TUNIO 2024 // Age Pendant // TO DO: // current loop is 17 to 18 milliseconds long - need less than 5 for accurate centi-second counting // Libraries #include &lt;SPI.h&gt; #include &lt;Wire.h&gt; #include &lt;DS3231.h&gt; #include &lt;Adafruit_GFX.h&gt; #include &lt;Adafruit_SSD1306.h&gt; // OLED Setup ~ copied from example #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 32 // OLED display height, in pixels #define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin) #define SCREEN_ADDRESS 0x3C // See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32 Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &amp;Wire, OLED_RESET); // RTC Setup RTClib myRTC; // Initializations for periodic sync with RTC uint32_t remote_time = 0; uint32_t sync_interval_ms = 1800000; // sync with RTC every sync_interval_ms milliseconds // about an hour is good uint32_t last_millis_synced = 0; // the last time we synced with RTC uint32_t system_time = 0; // the local system time // Initializations for age calcs // QUESTION us 32 bit enough to store the age of someone? What if they live to 100? uint32_t born_utime = 788888888; // date of birth in unixtime // 788888888 uint32_t total_age_secs = 0; uint32_t sec_remainder = 0; uint8_t age_years = 0; uint8_t age_months = 0; uint8_t age_days = 0; uint8_t age_hours = 0; uint8_t age_mins = 0; uint8_t age_secs = 0; // initializations for centi-second counting uint8_t oldsec = -1; uint8_t newsec = -1; uint32_t offset = 0; uint8_t age_cs = 0; // screen saving vars bool invert = false; //// debug //uint32_t start_millis=0; //uint32_t end_millis=0; void setup() { Serial.begin(57600); Wire.begin(); delay(250); // display setup if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) { Serial.println(F(&quot;SSD1306 allocation failed&quot;)); for (;;); } display.dim(true); display.setTextColor(SSD1306_WHITE); display.clearDisplay(); display.setTextSize(2); // 1 default display.setRotation(3); //0 default, 1, 2, 3 // turn off built in LED pinMode(LED_BUILTIN , OUTPUT); digitalWrite(LED_BUILTIN , HIGH); // do first sync sync_time_with_rtc(); } void loop() { // //debug // start_millis = millis(); // sync every sync_interval_ms with RTC if (millis() - last_millis_synced &gt;= sync_interval_ms) { sync_time_with_rtc(); } // Calculate time elapsed since birth in years, months, etc. system_time = local_time_now(); total_age_secs = system_time - born_utime; // age in seconds age_years = num_time_units(total_age_secs, 31558149.756); // second arg is num of: secs in a year age_months = num_time_units(sec_remainder, 2629745.568); // ... secs in a month age_days = num_time_units(sec_remainder, 86401.505); // ... secs in day age_hours = num_time_units(sec_remainder, 3600); // ... in an hour age_mins = num_time_units(sec_remainder, 60); // ... in an minute age_secs = sec_remainder; // display the age calculated show_age_on_display(5, 3); // input top left coordinates of where the age will be displayed // //debug // end_millis = millis(); // Serial.println(end_millis - start_millis,DEC); } // Prints the provided age to the LCD with the correct formatting void show_age_on_display(int col, int line) { newsec = age_secs; if (newsec != oldsec) { offset = -1 * (millis() % 1000); if (age_secs % 11 == 0) {invert = ! invert;} // invert display to save pixels burning every 11 secs oldsec = age_secs; } display.clearDisplay(); display_at_location(age_years, col, line); display_at_location(age_months, col, line + (13 + 5) * 1); display_at_location(age_days, col, line + (13 + 5) * 2); display_at_location(age_hours, col, line + (13 + 5) * 3); display_at_location(age_mins, col, line + (13 + 5) * 4); display_at_location(age_secs, col, line + (13 + 5) * 5); age_cs = floor(((millis() + offset) % 1000) / 10); display_at_location(age_cs, col, line + (13 + 5) * 6); display.fillRect(0, display.height() - 18, display.width(), 18 - ((18 * age_cs) / 100), SSD1306_INVERSE); // progress bar completes every second display.invertDisplay(invert); display.display(); } // display integer value &lt;100 at given location with &quot;0&quot; padding void display_at_location(uint8_t value, uint8_t this_col, uint8_t this_line){ display.setCursor(this_col, this_line); if (value &lt; 10) display.print(F(&quot;0&quot;)); display.print(value, DEC); } // input seconds and returns number of whole time unit, sets remainder variable uint32_t num_time_units( uint32_t secs, float time_unit) { int num_units = floor(secs / time_unit); sec_remainder = secs - round(num_units * time_unit); return num_units; } // syncs time with the RTC: call on sync_interval, power ons, AND when wake from sleep void sync_time_with_rtc() { digitalWrite(LED_BUILTIN , LOW); // briefly flash the LED every sync with the RTC remote_time = myRTC.now().unixtime(); last_millis_synced = millis(); system_time = local_time_now(); digitalWrite(LED_BUILTIN , HIGH); } // fetches the unixtime according to Arduino uint32_t local_time_now() { return remote_time + floor((millis() - last_millis_synced) / 1000); } </code></pre>
<p>I see quite a bit of floating point computations here. Since the SAMD21 doesn't have a floating point unit, all float operations are implemented in software, which can be quite expensive. As an optimization, I suggest to stay as much as possible in the integer realm. For example:</p> <pre class="lang-cpp prettyprint-override"><code>uint32_t total_minutes = total_age_secs / 60; age_secs = total_seconds - total_minutes * 60; uint32_t total_hours = total_minutes / 60; age_mins = total_minutes - total_hours * 60; uint16_t total_days = total_hours / 24; age_hours = total_hours - total_days * 24; age_years = total_days / 365; uint16_t remaining_days = total_days - age_years * 365; age_months = remaining_days * 12 / 365; age_days = remaining_days - age_months * 365 / 12; </code></pre> <p>Note that there is some rounding here: a day is assumed to be exactly 86400 seconds instead of 86399.9999 (I don't know where you found the number 86401.505), a year is assumed to be 365 days, and all months are assumed to be equal. If you found this approximations too rough (mostly the year), you may use 365.25 = 1461 / 4 days per year and 1461 / 48 days per month. You can do this by replacing the last four lines with:</p> <pre class="lang-cpp prettyprint-override"><code>age_years = total_days * 4 / 1461; uint16_t remaining_days = total_days - age_years * 1461 / 4; age_months = remaining_days * 48 / 1461; age_days = remaining_days - age_months * 1461 / 48; </code></pre>
95547
|esp8266|string|eeprom|platformio|
String or unsigned char to uint8_t
2024-02-16T17:26:37.610
<p>I'm attempting to save a string to EEPROM of an ESP8266 radio and then read it back before I encrypt the data (evenutally I would like to save the encrypted data but I'm simplifing things at the moment). Here is the source code:</p> <pre><code>#include &lt;Arduino.h&gt; extern &quot;C&quot; { #include &quot;cryptoauthlib.h&quot; } #include &quot;aes_cbc.h&quot; #include &lt;EEPROM.h&gt; // Key Slot number uint8_t KEY_SLOT = (uint8_t)9; ATCAIfaceCfg cfg; ATCA_STATUS status; void writeStringToEEPROM(int addrOffset, const String &amp;strToWrite) { byte len = strToWrite.length(); EEPROM.write(addrOffset, len); for (int i = 0; i &lt; len; i++) { EEPROM.write(addrOffset + 1 + i, strToWrite[i]); } } String readStringFromEEPROM(int addrOffset) { int newStrLen = EEPROM.read(addrOffset); char data[newStrLen + 1]; for (int i = 0; i &lt; newStrLen; i++) { data[i] = EEPROM.read(addrOffset + 1 + i); } data[newStrLen] = '\0'; return String(data); } void setup() { Serial.begin(74880); // Init the constuctor for the library cfg.iface_type = ATCA_I2C_IFACE; // Type of communication -&gt; I2C mode cfg.devtype = ATECC608A; // Type of chip cfg.atcai2c.slave_address = 0X30; // I2C address of the Adafruit Breakout Board cfg.atcai2c.bus = 1; cfg.atcai2c.baud = 100000; cfg.wake_delay = 1500; // Delay of wake up (1500 ms) cfg.rx_retries = 20; atca_trace_config(stdout); } void loop() { ATCA_STATUS status = atcab_init(&amp;cfg); if (status != ATCA_SUCCESS) { Serial.println(F(&quot;atcab_init() failed : Code -&gt; 0x&quot;)); Serial.println(status, HEX); } writeStringToEEPROM(0, &quot;test&quot;); String retrievedString = readStringFromEEPROM(0); uint8_t plaintext = atoi(retrievedString.substring(1,3).c_str()); uint8_t iv[IV_LENGTH_CBC]; uint8_t cypherdata[sizeof(plaintext)]; Serial.println(&quot;Beginning of the encryption !&quot;); status = aes_cbc_encrypt(&amp;cfg, plaintext, sizeof(plaintext), iv, cypherdata, KEY_SLOT); if (status == ATCA_SUCCESS) { Serial.println(&quot;encrypted&quot;); } else { // See file atca_status.h for the code Error Serial.print(F(&quot;Impossible do the encryption | Code Error 0x&quot;)); Serial.println(status, HEX); return; } } </code></pre> <p>and here is the error message:</p> <p><a href="https://i.stack.imgur.com/eRGOW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eRGOW.png" alt="enter image description here" /></a></p> <p>EDIT**: Found out that the &quot;Save to EEPROM&quot; portion of my code wasn't working so I corrected that. Here is the new code:</p> <pre><code>#include &lt;Arduino.h&gt; extern &quot;C&quot; { #include &quot;cryptoauthlib.h&quot; } #include &quot;aes_cbc.h&quot; #include &lt;EEPROM.h&gt; // Key Slot number uint8_t KEY_SLOT = (uint8_t)9; ATCAIfaceCfg cfg; ATCA_STATUS status; void setup() { Serial.begin(74880); // Init the constuctor for the library cfg.iface_type = ATCA_I2C_IFACE; // Type of communication -&gt; I2C mode cfg.devtype = ATECC608A; // Type of chip cfg.atcai2c.slave_address = 0X30; // I2C address of the Adafruit Breakout Board cfg.atcai2c.bus = 1; cfg.atcai2c.baud = 100000; cfg.wake_delay = 1500; // Delay of wake up (1500 ms) cfg.rx_retries = 20; atca_trace_config(stdout); } void loop() { ATCA_STATUS status = atcab_init(&amp;cfg); if (status != ATCA_SUCCESS) { Serial.println(F(&quot;atcab_init() failed : Code -&gt; 0x&quot;)); Serial.println(status, HEX); } uint addr = 0; struct { uint val = 0; char str[16] = &quot;&quot;; } data; EEPROM.begin(512);// commit 512 bytes of ESP8266 flash (for &quot;EEPROM&quot; emulation) strcpy(data.str,&quot;test&quot;); EEPROM.put(addr,data); EEPROM.commit(); EEPROM.get(addr,data); Serial.println(String(data.str)); uint8_t plaintext = atoi(data.str); //uint8_t plaintext[16] = &quot;test&quot;; uint8_t iv[IV_LENGTH_CBC]; uint8_t cypherdata[sizeof(plaintext)]; uint8_t decryptdata[sizeof(plaintext)]; Serial.println(&quot;Beginning of the encryption !&quot;); status = aes_cbc_encrypt(&amp;cfg, &amp;plaintext, sizeof(plaintext), iv, cypherdata, KEY_SLOT); if (status == ATCA_SUCCESS) { Serial.println(&quot;encrypted&quot;); status = aes_cbc_decrypt(&amp;cfg, cypherdata, sizeof(cypherdata), iv, decryptdata, KEY_SLOT); if (status == ATCA_SUCCESS) { Serial.print(&quot;Decrypted text is : &quot;); for (size_t i = 0; i &lt; sizeof(decryptdata); i++) { Serial.print((char)decryptdata[i]); } Serial.println(&quot;&quot;); } } else { // See file atca_status.h for the code Error Serial.print(F(&quot;Impossible do the encryption | Code Error 0x&quot;)); Serial.println(status, HEX); return; } delay(1000); } </code></pre> <p>Now I'm seeing this in the terminal (no errors on compile!):</p> <pre><code>encrypted ERROR Decrypt : ATCA_BAD_PARAMI2C send 1 bytes to addr 0x30: 01 </code></pre> <p>When I change (the aes_cbc_encrypt function expects a length of 16)</p> <pre><code>sizeof(plaintext) </code></pre> <p>to</p> <pre><code>16 </code></pre> <p>I see:</p> <pre><code>Decrypted text is : ␀␀␀␀␀␀␀␀l��?���? </code></pre> <p>When I proved that the encrypt/decrypt portion of my code was working, this is what &quot;plaintext&quot; was:</p> <pre><code> uint8_t plaintext[16] = &quot;test&quot;; </code></pre>
<p>The function <a href="https://en.cppreference.com/w/c/string/byte/atoi" rel="nofollow noreferrer"><code>atoi()</code></a> tries to interpret a string as a textual representation of a number written in decimal. For example, <code>atoi(&quot;42&quot;)</code> returns the integer 42. Here:</p> <pre class="lang-cpp prettyprint-override"><code>uint8_t plaintext = atoi(data.str); </code></pre> <p>You are asking it to interpret <code>&quot;test&quot;</code>, which does not look like a number. In such a case, <code>atoi()</code> returns zero. I do not know what was your intent, but it was probably not this.</p> <p>Further down, you have</p> <pre class="lang-cpp prettyprint-override"><code>uint8_t cypherdata[sizeof(plaintext)]; uint8_t decryptdata[sizeof(plaintext)]; </code></pre> <p>Given that <code>plaintext</code> is a single byte, its length is one. Thus this is declaring two arrays of length one. Again, you probably meant something else.</p> <hr /> <p>From you comment, I understand that you want <code>plaintext</code> to represent the string <code>&quot;test&quot;</code> as an array of <code>uint8_t</code>. Since both <code>char</code> and <code>uint8_t</code> represent bytes, no conversion is needed. You can simply use the address of the original <code>char</code> array and “pretend” it is the address of an array of <code>uint8_t</code>:</p> <pre><code>uint8 *plaintext = (uint8_t *) data.str; </code></pre>
95589
|esp8266|led|button|reset|neopixel|
strip.clear() is not clearing/turning off the NeoPixel strip after resetting the ESP8266
2024-02-21T11:29:26.697
<p>In the code below which is running on a WEMOS D1 (ESP8266), a NeoPixel strip turns on 1 LED in red which moves left to right and then right to left whilst the board attempts to connect to Wi-Fi in the <code>while (WiFi.status() != WL_CONNECTED)</code> loop.</p> <p>If I hold down the button 'SW' connected to the pin D7 and click the reset button, the code turns on the 7 segment display, however the LED on the NeoPixel strip which was last lit remains on (as though it is 'frozen'). Once I exit the <code>while(configRPM &gt; 0){</code> loop, all goes back to normal and the NeoPixel strip unfreezes.</p> <p>I thought <code>strip.clear()</code> would clear the NeoPixel strip near the start of <code>setup()</code> but that does not appear to work. I thought adding a delay might fix it and it hasn't. Why is the NeoPixel strip not turning off when the board is reset and how do I fix it?</p> <p>Here is the code:</p> <pre><code>#include &lt;ESP8266WiFi.h&gt; // Include the ESP8266WiFi library. #include &lt;ELMduino.h&gt; // Include the ELMduino library. #include &lt;Adafruit_NeoPixel.h&gt; // Include the Adafruit NeoPixel library. #include &lt;Encoder.h&gt; #include &lt;TM1637Display.h&gt; #include &lt;EEPROM.h&gt; // Define the addresses where you want to store your variables in EEPROM #define ADDR_MINIMUMRPM 0 #define ADDR_MAXIMUMRPM (ADDR_MINIMUMRPM + sizeof(int)) #define CLK D1 #define DT D2 #define SW D7 #define CLK_TM1637 D5 #define DIO_TM1637 D6 TM1637Display display(CLK_TM1637, DIO_TM1637); Encoder encoder(CLK, DT); int configTriggered = 0; int buttonReleased = 0; int configRPM = 0; int minimumRPM = 2500; int maximumRPM = 6000; int currentPosition = minimumRPM - 100; int oldPosition = -1000; int newPosition = 0; // WiFi credentials and server details const char* ssid = &quot;WIFI_OBDII&quot;; // Set the SSID of the ELM327. WiFiClient client; // WiFiClient is a class that defines how to create objects that represent WiFi clients. client is an object of this class, allowing the ESP8266 to function as a WiFi client. ELM327 myELM327; // Creates an object named myELM327 of the ELM327 class. This object represents an instance of the ELM327 OBD-II interface, allowing the program to interact with it using methods provided by the ELM327 class. const int neopixel_Count = 16; // Indicates that there are 16 NeoPixels in the strip, with IDs ranging from 0 to 15. Adafruit_NeoPixel strip(neopixel_Count, D8, NEO_GRB + NEO_KHZ800); // Initializes a NeoPixel strip object with 16 NeoPixels connected to pin D2, using the color order Green-Red-Blue and a data transmission frequency of 800 KHz. const int potentiometer_Pin = A0; // Sets the constant variable potentiometer_Pin to A0, being the ID of the analog pin int rpm = 0; // RPM variable which is taken from the car and used in the code. void setup() { // Setup function to initialize NeoPixels and establish WiFi and ELM327 connections. pinMode(SW, INPUT_PULLUP); Serial.begin(9600); display.clear(); strip.begin(); // Initialize NeoPixels. delay(100); strip.clear(); // Initialize all pixels to 'off'. EEPROM.begin(sizeof(minimumRPM) + sizeof(maximumRPM)); EEPROM.get(ADDR_MINIMUMRPM, minimumRPM); EEPROM.get(ADDR_MAXIMUMRPM, maximumRPM); if (digitalRead(SW) == LOW){ configRPM = 1; display.setBrightness(0x0f); // Set brightness to maximum delay(50); } while(configRPM &gt; 0){ if (digitalRead(SW) == HIGH) { buttonReleased = 1; delay(50); } if (digitalRead(SW) == LOW &amp;&amp; buttonReleased == 1 &amp;&amp; configRPM == 1) { buttonReleased = 0; configRPM = 2; minimumRPM = currentPosition; Serial.println(&quot;Value saved for minimum RPM is &quot; + String(minimumRPM)); currentPosition = maximumRPM; display.showNumberDec(currentPosition); delay(50); // Debounce delay } if (digitalRead(SW) == LOW &amp;&amp; buttonReleased == 1 &amp;&amp; configRPM == 2) { buttonReleased = 0; configRPM = 0; maximumRPM = currentPosition; Serial.println(&quot;Value saved for maximum RPM is &quot; + String(maximumRPM)); display.clear(); EEPROM.put(ADDR_MINIMUMRPM, minimumRPM); EEPROM.put(ADDR_MAXIMUMRPM, maximumRPM); EEPROM.commit(); EEPROM.end(); delay(50); // Debounce delay } newPosition = encoder.read(); if (newPosition != oldPosition) { if (newPosition &gt; oldPosition) { currentPosition += 100; // Increase by 100 for each clockwise turn } else { currentPosition -= 100; // Decrease by 100 for each counterclockwise turn } // Limiting the current position within 0 to 9990 if (currentPosition &lt; 0) { currentPosition = 0; } else if (currentPosition &gt; 9900) { currentPosition = 9900; } display.showNumberDec(currentPosition); oldPosition = newPosition; } } Serial.println(&quot;Connecting to &quot; + String(ssid)); // Print the SSID in the serial monitor. WiFi.mode(WIFI_STA); // Set the Wi-Fi mode as 'station' where the ESP8266 act as a client of a network. WiFi.begin(ssid); // Initates the process for connecting to the Wi-Fi network of the ELM327. while (WiFi.status() != WL_CONNECTED) { // While the Wi-Fi status of the ESP8266 is not connectied to the ELM327 Wi-Fi network, execute the following code. movePixels(&quot;right&quot;, neopixel_Count, 100); // Move from the left most LED to the right most LED with a delay of 100 milliseconds. movePixels(&quot;left&quot;, neopixel_Count, 100); // Move from right most LED to left most LED with a delay of 100 milliseconds. Serial.print(&quot;.&quot;); // Print &quot;.&quot; in the serial monitor. } Serial.println(&quot;\nConnected to Wifi. The IP address of the ESP8266 is: &quot; + WiFi.localIP().toString()); // Print the IP address of the ESP8266. if (!client.connect(IPAddress(192, 168, 0, 10), 35000)) { // This line tries to connect the client object to a server at the IP address 192.168.0.10 and port 35000. If the connection fails, it executes the code inside the if block. Serial.println(&quot;Connection to ELM327 failed. Resetting and restarting the ESP8266.&quot;); // If the connection fails, print this line. ESP.reset(); // completely resets the ESP8266 microcontroller, disconnecting it from any Wi-Fi network and restarting its setup process defined in the setup() function. } myELM327.begin(client); // Initialize ELM327. } void loop() { // Loop function to continuously read RPM and update NeoPixels. rpm = myELM327.rpm(); // Read the RPM from the ELM327. if (myELM327.nb_rx_state == ELM_SUCCESS) { // Check for ELM327 communication status. If successful, do the following. Serial.print(&quot;RPM: &quot; + rpm); // Print the RPM to the serial monitor. updateNeopixels(rpm); // Update the NeoPixels based on RPM. } else if (myELM327.nb_rx_state != ELM_GETTING_MSG) { // Check if the ESP8266 is not currently receiving a message from the ELM327. myELM327.printError(); // Print ELM327 error if communication is not successful. } } void updateNeopixels(int rpm) { // Function to update NeoPixels based on RPM strip.clear(); // Clear all NeoPixels. if (rpm &gt;= 2500 &amp;&amp; rpm &lt; 5900) { // If the RPM is between the two values, do the following. The max RPM for this loop is higher to make all LEDs red for between 5800 and 5900. // Specifying the number of LEDs on the left and right to create a converging effect. int leftIndex = map(rpm, 2500, 5800, 0, neopixel_Count / 2 - 1); // Map the RPM from 2500 to 5800 to the range of 0 to 7. int rightIndex = neopixel_Count - 1 - leftIndex; // Take the leftIndex from 15. // For example, if the RPM is 5800, leftIndex = 7 and rightIndex = 8. // Map RPM to colors int red = map(constrain(rpm, 2500, 5800), 2500, 5800, 0, 255); // Map RPM to the amount of 'red' of the LEDs. The higher the RPM, the more red. int green = map(constrain(rpm, 2500, 5800), 2500, 5800, 255, 0); // Map RPM to the amount of 'green' of the LEDs. The higher the RPM, the less green. // For example, if the RPM is 5800, red = 255 and green = 0. This will apply to all LEDs to be lit. // Left side of the strip for (int i = 0; i &lt;= leftIndex; i++) { // The loop increments i by 1 whilst i &lt;= leftIndex, moving towards the right end of the strip. i++ is done after the body of the loop completes. strip.setPixelColor(i, strip.Color(red, green, 0)); // Set the color of the NeoPixel matching the ID of i. } // Right side of the strip (mirroring the left side) for (int i = neopixel_Count - 1; i &gt;= rightIndex; i--) { // The loop decreases by 1 whilst i &gt;= rightIndex, moving towards the left end of the strip. i-- is done after the body of the loop completes. strip.setPixelColor(i, strip.Color(red, green, 0)); // Set the color of the NeoPixel matching the ID of i. } } else if (rpm &gt;= 5900) { // If the RPM is at least 5900, do the following. for (int i = 0; i &lt; neopixel_Count; i++) { // The loop increments i by 1 whilst i &lt; neopixel_Count (16) as you can't send a single command to change the colour of all LEDs. strip.setPixelColor(i, strip.Color(255, 0, 255)); // Set the color of each NeoPixel to purple. } } strip.setBrightness(map(analogRead(potentiometer_Pin), 0, 1023, 0, 255)); // Map the potentiometer value to brightness range (0-255) and set the strip brightness accordingly. 1023 is the max value obtainabled from the analog-to-digital (ADC) converter. strip.show(); // Update the NeoPixel strip. } void movePixels(String direction, int numPixels, int delayTime) { // Function to move NeoPixels from left to right and then right to left. for(int i = 0; i &lt; numPixels; i++) { // The loop increments i by 1 whilst i &lt; numPixels (16). int index; if (direction == &quot;right&quot;) { // If direction is equal to 'right'... index = i; // Set index to i. } else if (direction == &quot;left&quot;) { // If direction is equal to 'left'... index = numPixels - 1 - i; // Set index to numPixels (16) - 1 - i. } else { // Handle an invalid direction input (neither right or left). return; // Exit the function with no response. } strip.setPixelColor(index, strip.Color(255, 0, 0)); // Set the LED which shares the ID of index as red. strip.setBrightness(map(analogRead(potentiometer_Pin), 0, 1023, 0, 255)); // Map the potentiometer value to brightness range (0-255) and set the strip brightness accordingly. 1023 is the max value obtainabled from the analog-to-digital (ADC) converter. strip.show(); // Update the NeoPixel strip. delay(delayTime); // Adjust the delay based on potentiometer value. strip.setPixelColor(index, 0); // Turn off the LED at the current position. } } </code></pre>
<p>We can have a look at the <code>clear()</code> function inside the Adafruit_Neopixel library. In Adafruit_Neopixel.cpp you can find at line 3396 (searching for <code>clear(void)</code> will get you there):</p> <pre><code>void Adafruit_NeoPixel::clear(void) { memset(pixels, 0, numBytes); } </code></pre> <p>This is a very short function. <code>memset()</code> sets all bytes in a defined range to the provided value. So all bytes in <code>pixels</code> will be set to zero. Though this is only the libraries internal memory. <strong>There is no IO action here, no code sending data to the Neopixels.</strong></p> <p>That means: <code>clear()</code> only acts on the libraries internal representation of the strip, just like <code>setPixel()</code> and its siblings. <strong>To actually send the data to the Neopixels you still need to call <code>strip.show()</code></strong>, which then takes the libraries internal representation of the strip and sends the data out through the digital pin to the Neopixels.</p> <p>I want to encourage people to look into the source code of libraries, they use. When you learn how to read them, you can get quick answers even without understanding the actual full implementation of the library.</p>
95604
|arduino-ide|assembly|compiler|
Removing the L from F_CPU in assembly
2024-02-23T03:56:27.297
<p>I am developing a mixed c++ /asm project. In the asm I am using F_CPU to do some busy waiting as follows. However, by default, the F_CPU is defined with a trailing L (for long). The asm is not able to cope with the L. I can fix this by manually defining a new define in the asm, but that's a pretty dirty solution. What's the correct way to fix this?</p> <pre><code>.macro _delay_1u .rept (F_CPU/1000000) nop .endr .endm </code></pre>
<p>Just as a complement to the busybee's answer: <a href="https://www.nongnu.org/avr-libc/user-manual/group__util__delay.html" rel="nofollow noreferrer">the avr-libc provides the macros <code>_delay_ms()</code> and <code>_delay_us()</code></a> for busy-wait delays. Internally, they use <code>__builtin_avr_delay_cycles()</code> and <code>F_CPU</code> to provide the required number of delay cycles. For example, on an Uno,</p> <pre class="lang-cpp prettyprint-override"><code>_delay_us(0.25); // delay for 0.25 µs </code></pre> <p>compiles to</p> <pre class="lang-lisp prettyprint-override"><code>rjmp . ; 2 cycles rjmp . ; 2 cycles </code></pre> <p>which takes exactly 0.25 µs (4 cycles at 16 MHz) and takes less code space than four <code>nop</code>s.</p>
95616
|ir|arduino-motor-shield|remote-control|hc-sr04|l298n|
Problem adding IR receiver to smart car
2024-02-25T19:12:06.883
<p>I’m making a smart car using an arduino uno, sensor shield v5, motor control with a L298N and a servo motor + HC-SR04 ultrasound sensor. I want to add a IR receiver on the board so I can also control the car with a remote.</p> <p>The problem is when I add in the code for the IR Receiver and make the 3 additional connections, the right motor doesn’t respond anymore, it only moves at the beginning, though slower than the left one during the initial setup, then only the left motor functions properly.</p> <p>Here is the whole code with comments next to the IR-Receiver specific code:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;Servo.h&gt; #include &lt;IRremote.h&gt; //IR Receiver Servo servo ; const int trigPin = 13; const int echoPin = 12; const int servoPin = 11; const int enAPin = 6; const int in1Pin = 7; const int in2Pin = 5; const int in3Pin = 4; const int in4Pin = 2; const int enBPin = 3; const int receiverPin = 9; //IR Receiver IRrecv irrecv(receiverPin); //IR Receiver decode_results signals; //IR Receiver enum Motor { LEFT, RIGHT }; void go(enum Motor m, int speed) { digitalWrite (m == LEFT ? in1Pin : in3Pin , speed &gt; 0 ? HIGH : LOW ); digitalWrite (m == LEFT ? in2Pin : in4Pin , speed &lt;= 0 ? HIGH : LOW ); analogWrite(m == LEFT ? enAPin : enBPin, speed &lt; 0 ? -speed : speed ); } void testMotors () { static int speed[8] = { 128, 255, 128, 0 , -128, -255, -128, 0}; go(RIGHT, 0); for (unsigned char i = 0 ; i &lt; 8 ; i++) go(LEFT, -speed[i]), delay(200); for (unsigned char i = 0 ; i &lt; 8 ; i++) go(RIGHT, speed[i]), delay(200); } unsigned int readDistance() { digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); unsigned long period = pulseIn(echoPin, HIGH); return period * 343 / 2000; } #define NUM_ANGLES 7 unsigned char sensorAngle[NUM_ANGLES] = {60, 70, 80, 90, 100, 110, 120}; unsigned int distance [NUM_ANGLES]; void readNextDistance() { static unsigned char angleIndex = 0; static signed char step = 1; distance[angleIndex] = readDistance(); angleIndex += step ; if (angleIndex == NUM_ANGLES - 1) step = -1; else if (angleIndex == 0) step = 1; servo.write(sensorAngle[angleIndex]); } void setup () { Serial.begin(9600); //IR Receiver irrecv.enableIRIn(); //IR Receiver pinMode(trigPin , OUTPUT); pinMode(echoPin, INPUT); digitalWrite(trigPin, LOW); pinMode(enAPin, OUTPUT); pinMode(in1Pin, OUTPUT); pinMode(in2Pin, OUTPUT); pinMode(in3Pin, OUTPUT); pinMode(in4Pin, OUTPUT); pinMode(enBPin, OUTPUT); servo.attach(servoPin); servo.write(90); go(LEFT, 0); go(RIGHT, 0); testMotors(); servo.write(sensorAngle[0]); delay(200); for (unsigned char i = 0 ; i &lt; NUM_ANGLES ; i ++) readNextDistance(), delay (200); } void loop () { //IR Receiver: if (irrecv.decode(&amp;signals)) { Serial.println(signals.value); irrecv.resume(); if (signals.value == 0xFFA25D) { Serial.println(&quot;yeees&quot;); } } readNextDistance (); unsigned char tooClose = 0; for (unsigned char i = 0 ; i &lt; NUM_ANGLES ; i++) if (distance[i] &lt; 200) tooClose = 1; if (tooClose) { go(LEFT, 180); go(RIGHT, -80); } else { go(LEFT, -180); go(RIGHT, 180); } delay (50); } </code></pre>
<p>Finally found the problem: it is due to the IRremote library using the same timers than the Servo.</p> <p>Solutions are to change the specified timer that the IRremote library uses in the library files (didn't work for me though) <strong>or</strong> to not use a library for either the IR receiver or the Servo <strong>or</strong> to change the physical connection of the component plugged in a pin also used by a timer.</p> <p><a href="https://forum.arduino.cc/t/problem-adding-ir-receiver-to-smart-car/1228441/5" rel="nofollow noreferrer">Link to an Arduino Forum post suggesting an alternative for controlling the Servo without a library</a></p>
95651
|1-wire|
How are "unique IDs" generated for 1wire devices?
2024-03-02T19:20:18.707
<p>If I wanted to make my own 1wire device, I would need to give it a &quot;globally unique&quot; 48-bit identifier.</p> <p>How are these identifiers generated? How can we guarantee no identifier conflicts with another brand's devices?</p>
<p>Interesting question. After searching for a while I have not found a definite answer, but some good hints.</p> <p>The 1-wire protocol was created by Dallas, which as later bought by Maxim Integrated. Thus the company Maxim has now control over it. They market the protocol with the explicit feature, that each device, that they manufacture, has a unique ID/serial number. They are the ones controlling it. I'm not sure how it works with other manufacturers, though this uniqueness probably only covers Maxims devices and the ones, where the respective manufacturer has a corresponding agreement with Maxim.</p> <p>So you cannot be sure, that any ID you generate is unique in the group of all other devices. You can try to use a different family code in the device address (the 48bit is only a part of the actual address, together with 8 bit family code and 8 bit checksum), specifically one, that is currently not in use by Maxim. I've found <a href="https://www.analog.com/en/resources/technical-articles/1wire-software-resource-guide-device-description.html" rel="nofollow noreferrer">this technical article</a> with a list of 1-wire device families. It states, that it may not include all device families, but it is the only list, that I found.</p> <p>As you wrote &quot;we&quot;: Creating IDs unique to a whole industry can only be guaranteed by going into an agreement with major industry players (provided they want to do such agreements). Otherwise your guarantees are always limited. You can stay away from the most common devices (with an unused family code) and make sure, that your organization gives out each device ID only ones.</p>
95683
|arduino-uno|arduino-nano|sensors|
Arduino Uno/Nano + ML
2024-03-06T13:40:42.147
<p>I couldn't find any clear answers elsewhere, hence I'm asking here. I have a TensorFlow/TensorFlow Lite model which I have already trained on some sensor data. Now, how can I utilize this model on my Arduino Nano/Uno to perform some other functions like moving a motor?</p> <p>Any help would be appreciated!</p> <p>Thanks</p>
<p>The <a href="https://www.tensorflow.org/lite/microcontrollers" rel="nofollow noreferrer">documentation of Tensorflow lite</a> states:</p> <blockquote> <p>The core runtime just fits in 16 KB on an Arm Cortex M3 and can run many basic models.</p> </blockquote> <p>So the Tensorflow lite runtime itself needs 16kB of - I guess - RAM. That would be 8 times of what the Uno/Nano actually has. If they mean program memory, then it would fit, since Uno/Nano has 32kB of flash.</p> <p>Though it would still not work:</p> <blockquote> <p>TensorFlow Lite for Microcontrollers is written in C++ 17 and requires a 32-bit platform.</p> </blockquote> <p>The Uno/Nano uses the Atmega328p, which is an 8-bit microcontroller.</p> <p>So all in all: No, you cannot use Tensorflow lite on an Uno/Nano. You should look at the &quot;Supported Platforms&quot; section of the linked Tensorflow Lite documentation to choose a board, that fits your needs.</p>
95708
|serial|arduino-mega|interrupt|
interrupt from a button and wait until serial port 1 has a message
2024-03-08T08:45:31.600
<p>I'm a little bit loss because I'm learning how to use the interruptions on Arduino. I'm creating a program to read an RFID code that arrives if an RFID transmitter is close to the antenna (a little antenna board RFID). I have two operating modes: one where I associate my board to an RFID, so I will act only where my RFID code is identified ( I save the RFID code on the board). and another mode where I read all the RFID codes and I save it.</p> <p>I have one configuration step where if the user push a button, I want to wink a led to indicate that we are waiting for the presentation of the RFID code to associate to the board. I try to make a code and I have some problems to get out of the condition where I'm waiting for the RFID code (serial1).</p> <p>Here is my code:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;Wire.h&gt; //const int reception_rfid = 15; const int btnAssociation = 2; // bouton pour indiquer que l'on souhaite faire l'appareillage des RFID (interruption) const int SwitchModeConfig = 4; const int LedAssociationEnCours = A0; int compteurLedAsso; const int BUFFER_SIZE_RFID = 13; char buf[BUFFER_SIZE_RFID]; void setup() { Wire.begin(8); // join i2c bus with address #8 Wire.onRequest(requestEvent); // register event Serial.begin(9600); Serial1.begin(9600); pinMode(SwitchModeConfig, INPUT_PULLUP); pinMode(btnAssociation, INPUT_PULLUP); pinMode(LedAssociationEnCours, OUTPUT); ConfigurationAssociation(); digitalWrite(LedAssociationEnCours, HIGH); } void loop() { delay(100); } void ConfigurationAssociation(){ int stateSwitch = digitalRead(SwitchModeConfig); if(stateSwitch == LOW){ attachInterrupt(digitalPinToInterrupt(btnAssociation), InterruptAssociation, RISING); Serial.println(&quot;Mode association&quot;); }else{ detachInterrupt(digitalPinToInterrupt(btnAssociation)); Serial.println(&quot;Mode aleatoire&quot;); } } void InterruptAssociation(){ compteurLedAsso = 0; Serial.println(&quot;Ouverture de l'Association d'un code RFID&quot;); while (Serial1.available() == 0 &amp;&amp; compteurLedAsso &lt;= 600) { // clignoter la led rouge sur A0 digitalWrite(LedAssociationEnCours, LOW); delay(5000); digitalWrite(LedAssociationEnCours, HIGH); delay(5000); compteurLedAsso++; Serial.println(compteurLedAsso); } if(Serial1.available() &gt; 0){ int codeRFID = Serial1.readBytes(buf, BUFFER_SIZE_RFID); Serial.println(&quot;CodeRFID: &quot;); for(int i = 0; i &lt; codeRFID; i++) Serial.print(buf[i]); } //Serial.println(compteurLedAsso); //compteurLedAsso++; Serial.println(&quot;Fin de l'attente code RFID&quot;); } void requestEvent() { } </code></pre> <ol> <li><p>First problem: I know that when we are inside a interruption we can't count the time pass on a while, I would like to wink the led 2 minutes: waiting the presentation of the RFID code to save and once the 2 minutes pass away I get out of the interruption. How make to wait 2 minutes for RFID code on serial1 port inside an interruption? my reception RFID board works fine and TX is connected to RX1 (pin 19) of Arduino mega (I verify on another code where reading RFID works)</p> </li> <li><p>Second problem: when my board is inside the interruption that comes from a push button (connected on pin 2) I stay always on the while loop even when my RFID transmitter is reading an RFID code, I can't get out of and I don't know why! maybe you can help to understand and find a solution please?</p> </li> </ol>
<p>chrisl's answer brings many excellent points, and I highly recommend you study it in detail. There are just a few points I would personally add or amend:</p> <ul> <li>an ISR should probably not last more than a few tens of microseconds, and many bad things could happen during a 1 ms ISR (missed clock tics, lost serial input...)</li> <li>a <code>loop()</code> iteration should not take more than a few milliseconds</li> <li>there is no point in using an interrupt for reading a button: the user will keep the button pressed for many milliseconds, and you will have many opportunities for catching it in <code>loop()</code>; interrupts bring complexity that is only worth it when you have to deal with sub-millisecond timings</li> <li>do not worry about the size of an <code>enum</code> unless you need to care about sub-<strong>micro</strong>second timings</li> </ul> <p>Now, my take at this problem. The first step is to define the state machine. I may call the states <code>NORMAL</code> and <code>ASSOCIATION</code>. The transitions would be:</p> <ul> <li><code>NORMAL</code> → <code>ASSOCIATION</code> when a button press is detected</li> <li><code>ASSOCIATION</code> → <code>NORMAL</code> when either an RFID code is read or after a timeout</li> </ul> <p>My tentative implementation:</p> <pre class="lang-cpp prettyprint-override"><code>// Attempt to read an RFID without blocking. // Returns the found RFID code as a pointer to a NUL-terminated buffer, // or nullptr if no RFID is available right now. char *read_rfid() { // Implementation left as an exercise to the reader. } void loop() { static enum {NORMAL, ASSOCIATION} state; static uint32_t started_association; // association start time char *rfid = read_rfid(); switch (state) { case NORMAL: if (rfid) { Serial.print(&quot;Read RFID code: &quot;); Serial.println(rfid); } if (digitalRead(btnAssociation) == LOW) { Serial.println(&quot;Starting association&quot;); mode = ASSOCIATION; started_association = millis(); } break; case ASSOCIATION: if (rfid) { assocate_rfid(rfid); Serial.println(&quot;Association successful, code: &quot;); Serial.println(rfid); mode = NORMAL; } if (millis() - started_association &gt;= assocation_timeout) { Serial.println(&quot;Association timeout&quot;); mode = NORMAL; } break; } } </code></pre> <p>There are a few things I left out here, most notably:</p> <ul> <li>The LED blinking, which should be done in the style of the Blink Without Delay example</li> <li>The function <code>read_rfid()</code> that reads the serial port in a non-blocking fashion. For this, you will need to have a rule for deciding when a message is complete. This could be a message terminator (if the reader does send one) or a timeout.</li> </ul> <p>Finally, I would recommend you read a couple of blog posts by Majenko:</p> <ul> <li><a href="https://majenko.co.uk/blog/our-blog-1/the-finite-state-machine-26" rel="nofollow noreferrer">The Finite State Machine</a> is a tutorial on the implementation of finite state machines</li> <li><a href="https://majenko.co.uk/blog/our-blog-1/reading-serial-on-the-arduino-27" rel="nofollow noreferrer">Reading Serial on the Arduino</a> teaches you how to read the serial port in a non-blocking fashion.</li> </ul>
95730
|arduino-nano-every|
Whats the MPPZ 3610 on Arduino nano every
2024-03-10T10:58:14.407
<p>I'm curious what's the MPPZ chip on my Arduino nano everu</p>
<p>From Arduino Nano Every <a href="https://docs.arduino.cc/resources/datasheets/ABX00028-datasheet.pdf" rel="nofollow noreferrer">datasheet</a>:</p> <blockquote> <p>MPM3610 (DC-DC)</p> <ul> <li>Regulates input voltage from up to 21V with a minimum of 65% efficiency @minimum load</li> <li>More than 85% efficiency @12V</li> </ul> </blockquote>
95732
|pulsein|dht11|
How execution time of code instructions influences signal between Arduino and DHT11?
2024-03-10T12:50:12.223
<p>I am exemining code for DHT11 from CircuitGeeks, variant without using lib. The problem is a mismatch between DHT11/DHT22 protocol and signals, which are read from sensor in scetch. Despite this, sketch is working and I would like to find out how.</p> <pre><code>#define DHT11_PIN 12 unsigned long TON_TIME = 0; unsigned long TOFF_TIME = 0; unsigned char data_byte[5]; unsigned int data_packet[40]; unsigned char bit_data = 0; unsigned char checksum_byte = 0; int bit_counter = 0; void setup() { Serial.begin(9600); Serial.println(&quot;DHT11 Humidity &amp; Temperature Sensor\n&quot;); delay(1000);//Wait before accessing Sensor } void loop() { pinMode(DHT11_PIN, OUTPUT); digitalWrite(DHT11_PIN, LOW); delay(18); digitalWrite(DHT11_PIN, HIGH); pinMode(DHT11_PIN, INPUT_PULLUP); TOFF_TIME = pulseIn(DHT11_PIN, LOW); if (TOFF_TIME &lt;= 84 &amp;&amp; TOFF_TIME &gt;= 76) { while (1) { TON_TIME = pulseIn(DHT11_PIN, HIGH); if (TON_TIME &lt;= 28 &amp;&amp; TON_TIME &gt;= 20) { bit_data = 0; } else if (TON_TIME &lt;= 74 &amp;&amp; TON_TIME &gt;= 65) { bit_data = 1; } else if (bit_counter == 40) { break; } data_byte[bit_counter / 8] |= bit_data &lt;&lt; (7 - (bit_counter % 8)); data_packet[bit_counter] = bit_data; bit_counter++; } } checksum_byte = data_byte[0] + data_byte[1] + data_byte[2] + data_byte[3]; if (checksum_byte == data_byte[4] &amp;&amp; checksum_byte != 0) { Serial.println(&quot;Humidity: &quot;); for (int c = 0; c &lt;= 7; c++) { Serial.print(data_packet[c]); } Serial.print(&quot;\t&quot;); for (int c = 0; c &lt;= 7; c++) { Serial.print(data_packet[c + 8]); } Serial.print(&quot;\t&quot;); Serial.print(data_byte[0]); Serial.print(&quot;%&quot;); Serial.println(&quot; &quot;); Serial.println(&quot;Temperature: &quot;); for (int c = 0; c &lt;= 7; c++) { Serial.print(data_packet[c + 16]); } Serial.print(&quot;\t&quot;); for (int c = 0; c &lt;= 7; c++) { Serial.print(data_packet[c + 24]); } Serial.print(&quot;\t&quot;); Serial.print(data_byte[2]); Serial.print(&quot;C&quot;); Serial.println(&quot; &quot;); Serial.println(&quot;Checksum Byte: &quot;); for (int c = 0; c &lt;= 7; c++) { Serial.print(data_packet[c + 32]); } Serial.println(&quot; &quot;); Serial.print(&quot;CHECKSUM_OK&quot;); Serial.println(&quot;&quot;); Serial.println(&quot;&quot;); } bit_counter = 0; data_byte[0] = data_byte[1] = data_byte[2] = data_byte[3] = data_byte[4] = 0; delay(1000); } </code></pre> <p>Looking into the code there is 18 ms of LOW level for initialization. Then about 40 us of HIGH level, it can be considered as time between <code>digitalWrite(DHT11_PIN, HIGH);</code> and <code>TOFF_TIME = pulseIn(DHT11_PIN, LOW);</code> instructions. But then after 80 us of LOW level <code>TOFF_TIME = pulseIn(DHT11_PIN, LOW);</code> it should be 80 us HIGH level. Instead of this, the code is being continued by conditions for checking pulses length, which are responsable for data bits. If pulse length is 26-28 us it's 0, if 70 us - it's 1. I understand that with <code>TON_TIME = pulseIn(DHT11_PIN, HIGH);</code> instruction we will find length of HIGH pulses of data bits only. <br/> <a href="https://i.stack.imgur.com/7Xzy4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7Xzy4.png" alt="enter image description here" /></a></p> <p>Why 80 us HIGH level is passed, however this doesn't impact on interaction with sensor? Does it pass in time of executing instructions from <code> if (TOFF_TIME &lt;= 84 &amp;&amp; TOFF_TIME &gt;= 76)</code> to <code>TON_TIME = pulseIn(DHT11_PIN, HIGH); </code>?</p>
<p>At the end of the 80 µs LOW from the HDT11, <code>pulseIn(DHT11_PIN, LOW)</code> returns. At this point in time, the data line is HIGH, somewhere near the beginning of the positive 80 µs pulse. Now, the code executes the first <code>pulseIn(DHT11_PIN, HIGH)</code>.</p> <p>You cannot measure the length of a positive pulse if you missed the rising edge. Thus, as <code>pulseIn()</code> finds the line HIGH, it will first wait until it transition to LOW, then wait until in transitions back to HIGH, and only then starting timing.</p> <p>See for example the <a href="https://github.com/arduino/ArduinoCore-avr/blob/1.8.6/cores/arduino/wiring_pulse.S" rel="nofollow noreferrer">implementation of the counting loop in the AVR core</a>, or rather the C code that served to generate the assembly implementation. It has three waiting loops:</p> <ul> <li>wait for any previous pulse to end</li> <li>wait for the pulse to start</li> <li>wait for the pulse to stop</li> </ul>
95760
|serial|usb|uart|firmata|seeeduino-xiao|
Arduino board with StandardFirmata doesn't respond to C# and Python client
2024-03-13T18:04:35.733
<p>I have a Seeeduino XIAO board with Firmata running on it. I'm currently trying to write C# client to communicate with this board. I have tried using <a href="https://learn.microsoft.com/ru-ru/dotnet/api/iot.device.arduino?view=iot-dotnet-latest" rel="nofollow noreferrer">Iot.Device.Arduino</a>, <a href="https://github.com/SolidSoils/Arduino" rel="nofollow noreferrer">SolidSolis.Arduino</a> and <em>pyfirmata</em> for that purpose but I'm struggling with problem - board doesn't respond to any requests sent by my apps.</p> <p>However, when I use <a href="https://apps.microsoft.com/detail/9nblggh2041m?hl=en-us&amp;gl=US" rel="nofollow noreferrer">Windows Remote Arduino Experience</a> app, board is being successfuly found and I can control pins, retrieve info etc. <img src="https://i.stack.imgur.com/9TqAc.png" alt="Screenshot 1" /> <img src="https://i.stack.imgur.com/j1cGI.png" alt="Screenshot 2" /></p> <ul> <li>I use these programs to communicate with board:</li> </ul> <pre class="lang-csharp prettyprint-override"><code>using Iot.Device.Arduino; var arduino = new ArduinoBoard(&quot;COM3&quot;, 57600); Console.WriteLine(arduino.FirmataVersion.Major); // This throws System.TimeoutException </code></pre> <pre class="lang-python prettyprint-override"><code>import pyfirmata port = 'COM3' board = pyfirmata.Arduino(port) print(board.firmata_version) # prints 'None' </code></pre> <ul> <li><p><a href="https://github.com/firmata/arduino/blob/main/examples/StandardFirmata/StandardFirmata.ino" rel="nofollow noreferrer">StandardFirmata</a> runs on Arduino.</p> </li> <li><p>This was added into <code>Boards.h</code>:</p> </li> </ul> <pre class="lang-cpp prettyprint-override"><code>#elif defined(SEEED_XIAO_M0) #define TOTAL_ANALOG_PINS 11 #define TOTAL_PINS 17 // 11 digital / analog + 1 DAC output + 2 i2c + 3 spi #define VERSION_BLINK_PIN LED_BUILTIN #define PIN_SERIAL1_RX 7 #define PIN_SERIAL1_TX 6 #define IS_PIN_DIGITAL(p) ((p) &gt;= 0 &amp;&amp; (p) &lt;= 10) #define IS_PIN_ANALOG(p) ((p) &gt;= 0 &amp;&amp; (p) &lt;= 10) #define IS_PIN_PWM(p) ((p) &gt;= 1 &amp;&amp; (p) &lt;= 10) #define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) &amp;&amp; (p) &lt; MAX_SERVOS) // deprecated since v2.4 #define IS_PIN_I2C(p) ((p) == 4 || (p) == 5) // SDA = 4, SCL = 5 #define IS_PIN_SPI(p) ((p) == 4 || (p) == 10 || (p) == 9 || (p) == 8) // SS = A4 #define IS_PIN_SERIAL(p) ((p) == 6 || (p) == 7) #define PIN_TO_DIGITAL(p) (p) #define PIN_TO_ANALOG(p) (p) #define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) #define PIN_TO_SERVO(p) (p) // deprecated since v2.4 </code></pre> <p>I've tried to rebuild Windows Remote Arduino Experience app with modifications - I've made it log every bytes it sends to Arduino or receives from Arduino. Then I've tried sending those bytes manually but result was still the same - board was not responding</p> <p>There is a device in <code>Device manager</code>:</p> <ul> <li>USB device with Serial port (COM3) (ID - <code>USB\VID_2886&amp;PID_802F&amp;REV_0104&amp;MI_00</code>)</li> </ul> <p>P.S. How do I know that the board is not responding and it's not the app that doesn't work? The board has RX and TX leds, RX one blinks always but TX blinks only when I use Windows Remote Arduino Experience app.</p> <p>What I am doing wrong? Is there any error in setup or code I've written?</p>
<p>The problem was in serial port connection settings. When I used these i was finally able to get response from board:</p> <pre class="lang-csharp prettyprint-override"><code>var port = new SerialPort(&quot;COM3&quot;, 115600); port.Open(); port.Parity = Parity.None; port.StopBits = StopBits.One; port.DataBits = 8; port.Encoding = Encoding.UTF8; port.RtsEnable = true; port.DtrEnable = true; port.BreakState = false; </code></pre>
95768
|esp32|wifi|
Very slow to connect to WiFi with ESP32 (minutes, not seconds)
2024-03-14T15:38:04.640
<p>I am having some issues with connecting to WiFi with an ESP32 board. It is very sloooooooooow. The first few times I tried, I left it alone for 20 minutes and it still wasn't able to connect. So I thought it didn't work. So I tried to use MicroPython and ESP-IDF and they both worked, although MicroPython was somewhat slow (~10-20 seconds), but ESP-IDF was instantaneous. Then I went back to Arduino and this time it eventually connected after 260 seconds (&gt; 4 minutes). Another try took 420 seconds (7 minutes). Has anyone else seen similar issues?</p> <p>What I have tried:</p> <ul> <li>Tried another board of the same model to ensure it's not defective.</li> <li>Tried a different WiFi AP with the same results.</li> </ul> <p>Although MicroPython and ESP-IDF framework work fine, I am still hoping to stick with Arduino for its simplicity and my hatred for Python, but don't hold it against me if you're fond of it :-).</p> <p>My board: ESP-WROOM-32(<a href="https://rads.stackoverflow.com/amzn/click/com/B0B764963C" rel="nofollow noreferrer" rel="nofollow noreferrer">https://www.amazon.com/gp/product/B0B764963C</a>). In Arduino IDE, I'm choosing &quot;ESP32-WROOM-DA Module&quot;. I have also tried &quot;uPesy ESP32 Wroom DevKit&quot; with the same results.</p> <p>The core version is &quot;esp32 by Espressif Systems&quot; 2.0.11.</p> <p>My network setup: TP-Link EAP225, running as a dedicated AP, not a router. My router is Linksys WRT1900ACS running OpenWrt 19.07.2 r10947-65030d81f3.</p> <p>The other setup I tried is a D-Link DIR-842 running as both an AP and a router, although I didn't connect the upstream port.</p> <p>My code:</p> <pre><code>#include &lt;WiFi.h&gt; const char* ssid = &quot;delingtest&quot;; const char* password = &quot;XxxxxYyyy00&quot;; void setup() { Serial.begin(115200); Serial.println(millis()); // To time the connection Serial.print(&quot;Connecting to WiFi network &quot;); Serial.print(ssid); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); do { Serial.print(&quot;.&quot;); delay(5000); } while (!WiFi.isConnected()); Serial.println(&quot;done.&quot;); Serial.println(millis()); // To time the connection Serial.print(&quot;IP address: &quot;); Serial.println(WiFi.localIP()); } void loop() { } </code></pre> <p>Additional info:</p> <ul> <li>When I used MicroPython, I connected interactively. Reference: <a href="https://docs.micropython.org/en/latest/esp8266/tutorial/network_basics.html" rel="nofollow noreferrer">https://docs.micropython.org/en/latest/esp8266/tutorial/network_basics.html</a></li> <li>For ESP-IDF, I used sample code here: <a href="https://github.com/espressif/esp-idf/tree/master/examples/wifi/getting_started/station" rel="nofollow noreferrer">https://github.com/espressif/esp-idf/tree/master/examples/wifi/getting_started/station</a></li> <li>I checked the log on the DHCP server (running OpenWRT), the time between receiving the DHCP request and offering the IP address was quick (see below).</li> </ul> <pre><code>Wed Mar 13 16:57:55 2024 daemon.info dnsmasq-dhcp[13394]: DHCPDISCOVER(br-lan) 40:22:d8:78:7a:38 Wed Mar 13 16:57:55 2024 daemon.info dnsmasq-dhcp[13394]: DHCPOFFER(br-lan) 192.168.1.145 40:22:d8:78:7a:38 Wed Mar 13 16:57:55 2024 daemon.info dnsmasq-dhcp[13394]: DHCPREQUEST(br-lan) 192.168.1.145 40:22:d8:78:7a:38 Wed Mar 13 16:57:55 2024 daemon.info dnsmasq-dhcp[13394]: DHCPACK(br-lan) 192.168.1.145 40:22:d8:78:7a:38 esp32-787A38 </code></pre> <p>Edit:</p> <p>I added some code to do a ping to the gateway after establishing the connection:</p> <pre><code> IPAddress ip (192, 168, 1, 1); bool ret = Ping.ping(ip); </code></pre> <p>And timed it. Every ping took about 4-5 seconds. So, it's not just slow to connect to the WiFi network, it's also very slow do ping, and probably to do everything else.</p> <p>Edit on edit: After turning on verbose logging, I realized that what <code>ping</code> actually does is to the effect of <code>ping -c 5</code>, with 1 second between pings. So, it does take 4ish seconds no matter what. Originally I thought it only sent one ping per call.</p>
<p>Huh, I just tried a 3rd board and I think I have found the root cause. If the board is inserted in a breadboard. It's slooooooow, or even impossible to connect. But if I pull it out, it seems to connect in a few seconds. So, I guess the problem really is the breadboard interfering with the on-board antenna. I'll probably need to get a 32U with an external antenna connector for the final product.</p>
95769
|c|
Serial com register formula
2024-03-14T18:44:58.997
<p>i am working on a atmega328p, learning to uses its registers instead a coding with common arduino code.</p> <p>i've found this formula to get the baud rate on the Serial port (using USART protocol) :</p> <p><a href="https://i.stack.imgur.com/pLyub.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pLyub.png" alt="enter image description here" /></a></p> <p>how could i type this in C language ? or specifically in the arduino IDE ?</p> <p>--</p> <p>i made some researches and discovered that it could write it that way :</p> <pre><code>float _baudrate = (16000000/(16*9600)); </code></pre> <p>then i convert the value to int (because i need an integer value)</p> <pre><code>int _baudrate_int = (int)_baudrate;enter code here </code></pre> <p>all this for a 9600 baudrate of course.</p> <p>But when i do this, i don't understand why, the code does not calculate it right. i'm supposed to have 103-104 and i get 710.</p> <p>it will work if i type (16*9600) product manually. Which is 153600</p> <pre><code>float _baudrate = (16000000/153600); </code></pre> <p>then i get the right baudrate result. but what if i want the code to calculate everything ? how can i do ?</p> <p>where's my mistake with this line of code ?</p> <pre><code>float _baudrate = (16000000/(16*9600)); </code></pre>
<p>Here:</p> <blockquote> <pre class="lang-cpp prettyprint-override"><code>float _baudrate = (16000000/(16*9600) </code></pre> </blockquote> <p>other than the missing parenthesis and semicolon, you have an integer overflow. The issue is that, on AVR-based Arduinos, an <code>int</code> is only 16-bits long. The constants <code>16</code> and <code>9600</code> being small enough to fit in an <code>int</code>, they are implicitly given the <code>int</code> type. Then, their multiplication is also done with the <code>int</code> type, and the product overflows and wraps modulo 2<sup>16</sup> to 22528.</p> <p>You can fix this by giving either or both of these numbers the <code>L</code> suffix, which will make them use the <code>long</code> data type. Alternatively, if you want a floating point calculation, you can use <code>.0</code> as a suffix.</p> <p>Not that the avr-libc provides a header file with some macros for this calculation, which is then done by the preprocessor: <a href="https://www.nongnu.org/avr-libc/user-manual/group__util__setbaud.html" rel="nofollow noreferrer">&lt;util/setbaud.h&gt;: Helper macros for baud rate calculations</a>. You can use them as follows:</p> <pre class="lang-cpp prettyprint-override"><code>#define BAUD 9600 #include &lt;util/setbaud.h&gt; void set_baud_rate() { UBRR0 = UBRR_VALUE; #if USE_2X UCSR0A |= _BV(U2X0); #else UCSR0A &amp;= ~_BV(U2X0); #endif } </code></pre> <p><strong>Edit:</strong></p> <p>To answer the question in a comment: yes, the <code>L</code> suffix creates a <code>long</code> constant, and is thus similar to creating a <code>long</code> variable (except it is a constant instead of a variable).</p> <p>I suggest you take a look at the line below from setbaud.h. In the case where U2X0 is not needed, the baud rate register value is computed as:</p> <pre class="lang-c prettyprint-override"><code>#define UBRR_VALUE (((F_CPU) + 8UL * (BAUD)) / (16UL * (BAUD)) -1UL) </code></pre> <p>A few things to note:</p> <ul> <li>It is all computed with integers, no floating point. Actually, the computation is performed by the compiler, at build time, not by the Arduino.</li> <li>The suffix <code>UL</code> is for <code>unsigned long</code></li> <li>Adding 8 before dividing by 16 is a way to round the result to the nearest integer, instead of rounding to zero. Ties are rounded up.</li> <li>There is <code>-1UL</code> at the end, as this is required by the UART hardware (it is in the formula from the datasheet).</li> </ul>
95784
|arduino-uno|display|tft|
How to connect TFT screen (ST7735S) to Arduino?
2024-03-17T10:21:40.863
<p>I'm learning to work with Arduino and I decided to work with a TFT display (driver ST7735S, I connect to Arduino Uno), but I encountered a problem in the form that my contacts are labeled differently than in all the examples I looked at (example - no MOSI contacts/ MISO and CLK, instead of BL - BLK), because of which I am confused and cannot connect the screen correctly - please, help)</p> <p>Display photo:</p> <p><a href="https://i.stack.imgur.com/1RYk9.jpg" rel="nofollow noreferrer" title="Main"><img src="https://i.stack.imgur.com/1RYk9.jpg" alt="Main" title="Main" /></a></p> <p><a href="https://i.stack.imgur.com/p5nbF.jpg" rel="nofollow noreferrer" title="Driver"><img src="https://i.stack.imgur.com/p5nbF.jpg" alt="Driver" title="Driver" /></a></p>
<h4>Connections</h4> <p>Connections as follows:</p> <ul> <li>BLK -&gt; 5V</li> <li>CS -&gt; D10 (or anything, i.e. D9 - just change the <code>#define</code> below)</li> <li>DC -&gt; D9 (or anything, i.e. D8 - just change the <code>#define</code> below)</li> <li>RST -&gt; D8 (or anything, i.e. D7 - just change the <code>#define</code> below)</li> <li>SDA -&gt; D11</li> <li>SCL -&gt; D13</li> <li>VDD -&gt; 5V</li> <li>GND -&gt; GND</li> </ul> <h4>Using TFT library</h4> <p>You can use the TFT library:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;TFT.h&gt; #include &lt;SPI.h&gt; </code></pre> <p>With the following <code>#defines</code>:</p> <pre class="lang-cpp prettyprint-override"><code>#define CS 10 #define DC 9 #define RST 8 </code></pre> <p>Note: if you used different pins, then just change the numbers.</p> <p>Create an instance and initialise with:</p> <pre class="lang-cpp prettyprint-override"><code>TFT myDisplay = TFT(CS, DC, RST); myDisplay.begin(); </code></pre> <h4>Using GFX</h4> <pre class="lang-cpp prettyprint-override"><code>#include &lt;Adafruit_GFX.h&gt; #include &lt;Adafruit_ST7735.h&gt; #include &lt;SPI.h&gt; </code></pre> <p>With the following <code>#defines</code>:</p> <pre class="lang-cpp prettyprint-override"><code>#define CS 10 #define DC 9 #define RST 8 </code></pre> <p>Note: if you used different pins, then just change the numbers.</p> <p>Create instance<sup>1</sup>:</p> <pre class="lang-cpp prettyprint-override"><code>Adafruit_ST7735 myDisplay = Adafruit_ST7735(CS, DC, RST); </code></pre> <p>Initialise with</p> <pre class="lang-cpp prettyprint-override"><code>myDisplay.initR(INITR_BLACKTAB); </code></pre> <hr /> <h3>Further reading</h3> <ul> <li><a href="https://www.instructables.com/Beginner-Arduino-Using-a-18-Inch-TFT-Display/" rel="nofollow noreferrer">Beginner Arduino - Using a 1.8 Inch TFT Display</a></li> <li><a href="https://randomnerdtutorials.com/guide-to-1-8-tft-display-with-arduino/" rel="nofollow noreferrer">Guide to 1.8 TFT Display with Arduino</a></li> </ul> <h4>Footnote</h4> <p><sup>1</sup> Alternative instance creation, which is slower, but you can use different MOSI/SCLK pins (hence the additional <code>#defines</code>):</p> <pre class="lang-cpp prettyprint-override"><code>#define SCLK 13 // You can change this #define MOSI 11 // You can change this Adafruit_ST7735 myDisplay = Adafruit_ST7735(CS, DC, MOSI, SCLK, RST); </code></pre>
95844
|arduino-ide|compilation-errors|
Arduino_DebugUtils.h: No such file or directory
2024-03-26T13:10:59.293
<p>How to get rid of this error?</p> <pre class="lang-none prettyprint-override"><code>/storage/emulated/0/ArduinoDroid/userlibraries/Arduino_ConnectionHandler/src/Arduino_ConnectionHandler.h:26:34: fatal error: Arduino_DebugUtils.h: No such file or directory </code></pre>
<p>You need to install the <code>Arduino_DebugUtils</code> library.</p> <p>From <a href="https://www.arduino.cc/reference/en/libraries/arduino_debugutils/" rel="nofollow noreferrer">Arduino_DebugUtils</a>:</p> <blockquote> <p>To use this library, open the <a href="https://www.arduino.cc/en/Guide/Libraries" rel="nofollow noreferrer">Library Manager</a> in the Arduino IDE and install it from there.</p> </blockquote>
95855
|debounce|joystick|
Problems with reacting to joystick button press
2024-03-28T19:27:08.190
<p>I am trying to use a joystick in a project for device control. Pressing a joystick button should cause incrementing a variable. INPUT_PULLUP mode is used for internal button.</p> <p>As I understand it, when the button is not pressed there is a HIGH level on the GPIO pin, and there is a LOW level when the button is pressed. The signal read from the button in thd sketch is inverted to HIGH when the circuit is closed.</p> <p>I used some sketches for eliminating debounce, but in all cases when the button is pressed a stream of incoherent symbols occurs on the serial port. It happens both in the simulator and the IDE.</p> <p>What can cause this stream on the output when waiting for the message that button is pressed? The symbols also occured when I put a count-variable on the serial port. Does the button debounce look correct?</p> <pre class="lang-cpp prettyprint-override"><code>int Joystick_Y = A0; int Joystick_X = A1; int Joystick_but = 1; int X; int Y; int X_prev = 0; int Y_prev = 0; int butt_flag = 0; int butt; const unsigned long debounceDelay = 50; unsigned long last_press; void setup() { Serial.begin(9600); pinMode(Joystick_but, INPUT_PULLUP); } void loop() { butt = !digitalRead(Joystick_but); if (butt == 1 &amp;&amp; butt_flag == 0 &amp;&amp; millis() - last_press &gt; debounceDelay) { butt_flag = 1; last_press = millis(); Serial.println(&quot;Button was pressed!&quot;); } if (butt == 0 &amp;&amp; butt_flag == 1) { butt_flag = 0; } Y = analogRead(Joystick_Y); X = analogRead(Joystick_X); if (X &lt; 512 &amp;&amp; X &gt; 485) { X = 512; } if (Y &lt; 512 &amp;&amp; Y &gt; 485) { Y = 512; } if ((Y != Y_prev || X != X_prev) &amp;&amp; (X != Y)) { Serial.print(&quot;X: &quot;); Serial.print(X); Serial.print(&quot; Y: &quot;); Serial.println(Y); } Y_prev = Y; X_prev = X; delay(500); } </code></pre>
<p>As was mentioned in @chrisl 's comment: pin 1 on an Arduino Uno/Nano is the TX (transmit) pin for the Serial port. See <a href="https://www.arduino.cc/reference/en/language/functions/communication/serial/" rel="nofollow noreferrer">here</a>. This is the pin that is used to transmit serial data to the host.</p> <p>When the same pin is also used as the joystick button, pressing it will interfere with serial output, causing the incoherent symbols you see to be transmitted.</p> <p>Solution: Use a different (unused) pin.</p> <p>Another potential problem is the <code>delay (500)</code> at the end of your <code>loop()</code> which, as @chrisl also noted, interferes with your debounce and will cause your code to react to button presses and joystick movements very slowly.</p>
95864
|serial|programming|
Serial.println printing just after the previous string in same line
2024-03-30T11:15:45.323
<p>I wrote serial.println in my code but the string was printed in same line on serial moniter.</p> <pre><code>#include &lt;WiFi.h&gt;//for connecting esp32 to a wifi #include &lt;TinyGPS++.h&gt;//to obtain gps data from neo-6m gps module #define WIFI_SSID &quot;Airtel_pawa_4182&quot;//wifi name in simple words #define WIFI_PWD &quot;Ahuja6230&quot;//wifi password TinyGPSPlus GPS;//creating a gps object from tinygps++ library void setup() { Serial.begin(9600); //wifi setup{ WiFi.begin(WIFI_SSID, WIFI_PWD); Serial.println(&quot;connecting to wifi&quot;); while(WiFi.status() != WL_CONNECTED){ Serial.println(&quot;.&quot;); delay(1000); } Serial.println(&quot;Successfully connected to &quot;); Serial.print(WIFI_SSID); //} //gps setup{ Serial2.begin(9600); delay(1000); Serial.println(&quot;ESP32-GPS Tracker&quot;); Serial.println(&quot;Initializing...&quot;); //} } void loop() { } </code></pre> <p>In this code the string &quot;esp32-gps tracker&quot; is printing just after the previous string in same line on serial moniter.</p> <p>I tried running code again and again but it didn't work...</p> <p>I am using esp32 board(just a detail)</p> <p>What do i do?</p>
<p>To follow on from previous answer, your solution is to either:</p> <ul> <li>change the previous Serial.print() to a Serial.println() so that that text is followed by a line end, or</li> <li>add a \n to the front of the line you are having the problem with, so it starts with a new line, to make up for the &quot;missing&quot; new line in the previous Serial.print().</li> </ul>
95872
|arduino-uno-r4-wifi|
Smoke coming out of Arduino Uno R4 Minima
2024-03-31T09:39:24.513
<p>My Arduino Uno R4 Minima started smoking after connecting to a computer. I disconnected it and visually checked it and I saw this bubble as shown on this photo.</p> <p><a href="https://i.stack.imgur.com/7vWqx.jpg" rel="nofollow noreferrer" title="Photo of my Uno R4"><img src="https://i.stack.imgur.com/7vWqx.jpg" alt="Photo of my Uno R4" title="Photo of my Uno R4" /></a></p> <p>Can I recover my Uno from this to still use it or do I have to throw it away?</p>
<p>That's the buck-converter that connects to the external power supply.</p> <p>The board should still work when powered by the USB cable.</p> <p>Remove R11 to isolate the blown circuit if you like.</p> <p><a href="https://docs.arduino.cc/resources/schematics/ABX00080-schematics.pdf" rel="noreferrer">https://docs.arduino.cc/resources/schematics/ABX00080-schematics.pdf</a></p> <p><a href="https://i.stack.imgur.com/Fncg9.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Fncg9.jpg" alt="enter image description here" /></a></p>