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
89451
|arduino-uno|sensors|i2c|lcd|
I2C sensors not working when I connect to LCD 20X04
2022-04-25T08:46:09.443
<p>I am making a hydroponic nutrient monitoring system using Arduino Uno, Atlas Scientific EC sensor, pH sensor, and RTD (temperature) sensor in I2C mode. I also want to use LCD 20x04 to display the sensor reading so that will display the EC, pH, and temperature values. I connect all the SDA and SCL to pin A4 (SDA) and A5 (SCL), and powered all the sensors and LCD with 3.3 V. Each sensor's SDA and SCL are added with resistor 4.7 kOhm.</p> <p><a href="https://i.stack.imgur.com/t4PbL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t4PbL.jpg" alt="The Fritzing of my circuit" /></a></p> <p>I tested the code first by connecting my Arduino Uno to the RTD EZO circuit and sensors, without the LCD. The Serial Monitor successfully displays the data sensor reading of RTD, as well as 'No Data' for EC and pH as I do not connect the EC and pH sensors. But when I connect all the circuits and sensors, it can not detect the pH sensor. The most frustrating part is the LCD. The LCD at first displays the EC and RTD data, but only run for 5 minutes and freeze. The LCD sometimes only shows a &quot;0.00&quot; value for EC and RTD even though the Serial Monitor shows the data sensor reading.</p> <p>I want to know if there is something wrong with my code or maybe the problem with my own circuit.</p> <p>Here is the code:</p> <pre><code>#include &lt;Ezo_i2c.h&gt; #include &lt;Wire.h&gt; //enable I2C. #include &lt;LiquidCrystal_I2C.h&gt; Ezo_board ec = Ezo_board(100, &quot;EC&quot;); Ezo_board ph = Ezo_board(99, &quot;PH&quot;); Ezo_board temp = Ezo_board(102, &quot;RTD&quot;); LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 20, 4); bool reading_request_phase = true; //selects our phase uint32_t next_poll_time = 0; //holds the next time we receive a response, in milliseconds const unsigned int response_delay = 1000; //how long we wait to receive a response, in milliseconds void setup() //hardware initialization. { Serial.begin(9600); //enable serial port. Wire.begin(); //enable I2C port. Serial.println(&quot;ATLAS EZO I2C v2&quot;); Serial.print(&quot;Test date: &quot;); lcd.init(); lcd.backlight(); lcd.setCursor(1,1); lcd.print(&quot;ATLAS EZO I2C v2&quot;); lcd.setCursor(0,2); delay(3000); lcd.clear(); } void loop() { //the main loop. lcd.setCursor(0,1); lcd.print(&quot;EC: &quot;); lcd.setCursor(4,1); lcd.print(ec.get_last_received_reading()); lcd.setCursor(10,1); lcd.print(&quot;ppm&quot;); lcd.setCursor(0,2); lcd.print(&quot;pH: &quot;); lcd.setCursor(4,2); lcd.print(ph.get_last_received_reading()); lcd.setCursor(0,3); lcd.print(&quot;Temp.: &quot;); lcd.setCursor(7,3); lcd.print(temp.get_last_received_reading()); lcd.setCursor(13,3); lcd.print(&quot;C&quot;); if (reading_request_phase) //if were in the phase where we ask for a reading { //send a read command //to let the library know to parse the reading ec.send_read_cmd(); ph.send_read_cmd(); temp.send_read_cmd(); next_poll_time = millis() + response_delay; //set when the response will arrive reading_request_phase = false; //switch to the receiving phase } else //if were in the receiving phase { if (millis() &gt;= next_poll_time) //and its time to get the response { receive_reading(ec); //get the reading from the EC circuit receive_reading(ph); //get the reading from the PH circuit receive_reading(temp); //get the reading from the RTD circuit reading_request_phase = true; //switch back to asking for readings } } } void receive_reading(Ezo_board &amp;Sensor) { Serial.println(); Serial.print(Sensor.get_name()); //print the name of the EZO circuit Serial.print(&quot;: &quot;); Sensor.receive_read_cmd(); switch (Sensor.get_error()) //switch case based on what the response code is. { case Ezo_board::SUCCESS: Serial.print(Sensor.get_last_received_reading()); //the command was successful, print the reading break; case Ezo_board::FAIL: Serial.print(&quot;Failed &quot;); //means the command has failed. break; case Ezo_board::NOT_READY: Serial.print(&quot;Pending &quot;); //the command has not yet been finished calculating. break; case Ezo_board::NO_DATA: Serial.print(&quot;No Data &quot;); //the sensor has no data to send. break; } } </code></pre>
<p>Thank you for all your help. I now realize that I have made the wrong I2C circuits. Then I modified them and now the program and the sensors work perfectly.</p> <p>Here is my circuit now.</p> <p><a href="https://i.stack.imgur.com/BHgWA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BHgWA.jpg" alt="enter image description here" /></a></p>
89463
|shields|tft|
Turn off backlight on 2.4" TFT screen
2022-04-27T03:50:06.717
<p>I have an Arduino Due and a 2.4&quot; TFT screen shield <a href="http://www.lcdwiki.com/2.4inch_Arduino_Display#Program_Download" rel="nofollow noreferrer">this one</a>. I'm trying to turn off the backlight to save power but not having any luck. I'm using the super nice MCUFriend library:</p> <pre><code>#include &lt;Adafruit_GFX.h&gt; #include &lt;MCUFRIEND_kbv.h&gt; MCUFRIEND_kbv tft; </code></pre> <p>It has worked great to make buttons and graphics, it's just the backlight I can't figure out. There's a <a href="http://www.lcdwiki.com/res/MAR2406/ILI9341_Datasheet.pdf" rel="nofollow noreferrer">datasheet</a> for the driver chip and it has the following section to <code>Write CTRL Display</code>, which is what I imagine I need: <a href="https://i.stack.imgur.com/2VRCq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2VRCq.png" alt="enter image description here" /></a></p> <p>So I have been trying to send 0x00 to register 0x53, but the display stays lit. I've tried using MCUFriend_kbv to set it, then thought maybe I'm doing something wrong so I tried their sample <code>LCD_ID_readreg.ino</code> and added some lines:</p> <pre><code>readReg(0x54, 3, &quot;Read CTRL Display&quot;); lcdWriteRegister(0x53, 0x00); readReg(0x54, 3, &quot;Read CTRL Display after update&quot;); </code></pre> <p>I am not sure if I'm just misunderstanding something but the results show:</p> <pre><code>reg(0x0054) 00 00 00 Read CTRL Display reg(0x0054) 00 00 00 Read CTRL Display after update </code></pre> <p>I guess I was expecting the register to say the backlight was on before I update it, but it says <code>00</code> even before I make the update- yet the backlight is clearly on. Any idea what I'm missing? Maybe it's the comment there about &quot;control lines must be low&quot;? I have no idea what that means. If you search the document for &quot;control lines&quot; nothing comes up.</p> <p>The read above to 0x54 is because that's apparently where you read that register (unlike some where you call the same address to read/write): <a href="https://i.stack.imgur.com/AH6Uw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AH6Uw.png" alt="enter image description here" /></a></p>
<p>That screen has no backlight control. The same chip is used on many LCDs and whether the inbuilt backlight control registers are used very much depends on the screen the chip is attached to.</p> <p>If you want to control the backlight you will have to modify the shield to allow access to the right signal. I can't get a schematic for that specific screen, but from the images it looks like R2 on the underside may be a current limiting resistor for the backlight. Removing that resistor may turn off the back light, in which case you could replace it with a suitable transistor and similar resistor (you will have to check if it's high-side or low-side switched - does it provide power to the LEDs or sink it to ground) which you can control from a free GPIO pin.</p>
89465
|system-design|
Is there a standard way to describe devices?
2022-04-27T07:21:55.157
<p>I'm new to Arduino. I'm curious whether there is a standard way to record the plan of a device—for instance, if I wanted to share it or communicate the design to other people. I realize the short answer here might be, “yes, make a circuit diagram.” Are there perhaps widely used tools for producing those, perhaps with add-ons for Arduino boards? (I'd prefer a more semantic representation than, say, making a diagram in Inkscape.)</p>
<p>There is no plugin to a program like Inkscape - as far as I know. It doesn't make much sense to have one. With an Arduino circuit you normally want to show the real electrical connections. A block diagram without real electrical connections doesn't help much in reproducing the project. You can do it, but you will have to do it on your in in a graphic program. I think this is only helpful for rather big projects, where each block contains not only the Arduino but also many further components of that functional unit in your project.</p> <p>To show the circuit you basically have 2 options:</p> <ul> <li><p><strong>A wiring diagram:</strong> This is an image, mostly created via the software <a href="https://fritzing.org/" rel="noreferrer">Fritzing</a>, which shows a breadboard and the components of the project placed on it. The electrical connections are represented by colored lines. This is good for beginners, who cannot yet read a schematic and want to reproduce the circuit on their own breadboard. Though wiring diagrams, especially Fritzing, is only standard in the Arduino/Beginner world. The more you get into professional realm, the less you will see them. They look like this (please note the internal connections, that a breadboard has in its numbered rows):</p> <p><a href="https://i.stack.imgur.com/SDVyV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SDVyV.png" alt="enter image description here" /></a></p> </li> <li><p><strong>A schematic:</strong> A schematic is the standard way of describing any electronic circuit. For example look at the <a href="https://www.arduino.cc/en/uploads/Main/arduino-uno-smd-schematic.pdf" rel="noreferrer">Arduino Uno schematic</a>. Every part is represented by a symbol with pins. The pins get connected with lines (representing wires or PCB traces). There are many different softwares for creating schematics, for example Eagle, KiCAD, EasyEDA and Altium Designer. You can choose yourself what to use. Look at the options, that the softwares provide. Some are premium but have free options, others (like KiCAD) are open source. I personally use KiCAD. At least for KiCAD you can download part repository files (like <a href="https://www.opensourceagenda.com/projects/arduino-kicad-library" rel="noreferrer">this one</a>), which include Arduino boards, so that you can place them directly on your schematic. I'm sure there are similar resources for other programs as well. Export the resulting schematic to PDF or an image format so that everyone can read the schematic without having your program installed.</p> <p>An additional benefit in creating a schematic is, that all these programs also support creating a PCB layout from the schematic. So it gets easier to design a PCB from your circuit for DIY or ordered production.</p> </li> </ul>
89475
|sd-card|web-server|
How can I do web hosting having all the code of the site stored on an SD?
2022-04-27T12:32:09.643
<p>I am carrying out this project in which the Arduino acts as a web server and hosts a website in which I show the constantly updated temperature of a laboratory.</p> <p>The problem is running all this code in the Arduino: memory runs out easily.</p> <pre class="lang-cpp prettyprint-override"><code>void loop() { int value = analogRead(PIN_LM35); float temperature = value / 2.046; myFile = SD.open(&quot;temperature.txt&quot;); if (myFile) { Serial.println(temperature); } myFile.close(); EthernetClient client = server.available(); if (client) { while (client.connected()) { if (client.available()) { char c = client.read(); //read char by char HTTP request if (readString.length() &lt; 100) { //store characters to string readString += c; //Serial.print(c); } //if HTTP request has ended if (c == '\n') { Serial.println(readString); //print to serial monitor for debuging client.println(F(&quot;HTTP/1.1 200 OK&quot;)); //send new page client.println(F(&quot;Content-Type: text/html&quot;)); client.println(); refreshcounter = refreshcounter + 1; client.println(F(&quot;&lt;HTML&gt;&quot;)); client.println(F(&quot;&lt;HEAD&gt;&quot;)); client.print(F(&quot;&lt;meta http-equiv=\&quot;refresh\&quot; content=\&quot;2\&quot;&gt;&quot;)); client.println(F(&quot;&lt;meta name='apple-mobile-web-app-capable' content='yes' /&gt;&quot;)); client.println(F(&quot;&lt;meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' /&gt;&quot;)); client.println(F(&quot;&lt;TITLE&gt;TEMPERATURE SENSOR LAB01&lt;/TITLE&gt;&quot;)); client.println(F(&quot;&lt;/HEAD&gt;&quot;)); client.println(F(&quot;&lt;BODY&gt;&quot;)); client.println(F(&quot;&lt;H1&gt;TEMPERATURE SENSOR LAB01&lt;/H1&gt;&quot;)); client.println(F(&quot;&lt;hr /&gt;&quot;)); client.println(F(&quot;&lt;br /&gt;&quot;)); client.println(F(&quot;&lt;H2&gt;Arduino with Ethernet Shield&lt;/H2&gt;&quot;)); client.println(F(&quot;&lt;br /&gt;&quot;)); if (temperature &lt; 24) { client.println(&quot;&lt;p style=\&quot;font-size:50px; color:#8eff59; font-weight:bold; font-style:italic;\&quot;&gt;&quot;); client.println(temperature); client.println(&quot;&lt;/p&gt;&quot;); } else if (temperature &gt;= 24 &amp;&amp; temperature &lt;= 26) { client.println(&quot;&lt;p style=\&quot;font-size:50px; color:#ffbc03; font-weight:bold; font-style:italic;\&quot;&gt;&quot;); client.println(temperature); client.println(&quot;&lt;/p&gt;&quot;); } else { client.println(&quot;&lt;p style=\&quot;font-size:50px; color:#ff0303; font-weight:bold; font-style:italic;\&quot;&gt;&quot;); client.println(temperature); client.println(F(&quot;&lt;H2&gt;It is recommended to activate the air conditioner.&lt;/H2&gt;&quot;)); client.println(&quot;&lt;/p&gt;&quot;); } client.println(F(&quot;&lt;p style=\&quot;font-size:30px; color:#000000; font-weight:bold; ;\&quot;&gt;Date/Time: &lt;span id=\&quot;datetime\&quot;&gt;&lt;/span&gt;&lt;/p&gt;&quot;)); client.println(F(&quot;&lt;script&gt;&quot;)); client.println(F(&quot;var dt = new Date();&quot;)); client.println(F(&quot;document.getElementById(\&quot;datetime\&quot;).innerHTML = &quot; &quot;((\&quot;0\&quot;+dt.getDate()).slice(-2)) +\&quot;.\&quot;+ ((\&quot;0\&quot;+(dt.getMonth()+1)).slice(-2)) &quot; &quot;+\&quot;.\&quot;+ (dt.getFullYear()) +\&quot; \&quot;+ ((\&quot;0\&quot;+dt.getHours()).slice(-2)) +\&quot;:\&quot;+ ((\&quot;0\&quot;+dt.getMinutes()).slice(-2));&quot;)); client.println(F(&quot;&lt;/script&gt;&quot;)); client.println(&quot;&lt;svg width=\&quot;1000\&quot; height=\&quot;250\&quot;&gt;&quot;); client.println(&quot;&lt;rect width=\&quot;150\&quot; height=\&quot;5\&quot; fill=\&quot;gray\&quot;&gt;&quot;); client.println(&quot;&lt;animate attributeName=\&quot;x\&quot; from = \&quot;0\&quot; to =\&quot;10000\&quot; dur=\&quot;10s\&quot; fill=\&quot;freeze\&quot; /&gt;&quot;); client.println(&quot;&lt;/rect&quot;); client.println(&quot;&lt;/svg&gt;&quot;); client.println(&quot;&lt;br /&gt;&quot;); client.println(&quot;&lt;/BODY&gt;&quot;); client.println(&quot;&lt;/HTML&gt;&quot;); delay(1); //stopping client client.stop(); //clearing string for next read readString = &quot;&quot;; } } } } } </code></pre> <p>I put all the code of the web page on an external SD card to save memory. However, I don’t really know how to use it from the SD card.</p> <p>The problem that stops me is the fact that the site is not static, but is constantly updated with new temperature data.</p> <p>How can I do that?</p>
<p>You wrote:</p> <blockquote> <p>the site does not have to be static but constantly updated with new temperature data.</p> </blockquote> <p>A good option is to use Ajax. The basic idea is to split the site in two parts:</p> <ul> <li>a static part, potentially large, which contains all the user interface, the styling, the bells and whistles...</li> <li>a tiny, dynamic part that contains the data that is constantly updated <em>and nothing more</em>.</li> </ul> <p>The static part would be served from the SD card when the client sends a <code>GET /</code> request. The dynamic part would be served from another endpoint, for example as a reply to <code>GET /temperature</code>. Serving the dynamic part should be very simple, something like:</p> <pre class="lang-cpp prettyprint-override"><code>client.println(temperature); </code></pre> <p>Yes, just send the number as ASCII, no HTML formatting. If you ever need to send more than one number (e.g. multiple temperatures, or temperature and humidity), format them in <a href="https://www.json.org/" rel="nofollow noreferrer">JSON</a>. No need to use a library for that, plain <code>print()</code> should be cheaper and good enough:</p> <pre class="lang-cpp prettyprint-override"><code>client.print(F(&quot;{\&quot;temperature\&quot;:&quot;)); client.print(temperature); client.print(F(&quot;,\&quot;humidity\&quot;:&quot;)); client.print(humidity); client.print('}'); </code></pre> <p>On the client side, <code>JSON.parse()</code> gets the data back as an easy-to-use data structure.</p> <p>Here is a minimal example of what the static part could look like. Notice the JavaScript code sent to the client. This code is responsible for querying the temperature every 1000 milliseconds, and updating the Web page with the new data;</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;title&gt;Ajax test&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Ajax test&lt;/h1&gt; &lt;p&gt;Temperature: &lt;span id=&quot;temperature&quot;&gt;---&lt;/span&gt; °C&lt;/p&gt; &lt;script&gt; var data_field = document.getElementById(&quot;temperature&quot;); setInterval(function() { var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (request.readyState != 4) return; data_field.innerText = JSON.parse(request.responseText); }; request.open(&quot;GET&quot;, &quot;/temperature&quot;); request.send(); }, 1000); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>A few notes:</p> <ul> <li><p>This example is purposefully minimal. You may want to add some error checking, some decorations, some CSS and the such. Handling a temperature-dependent color also belongs to the client code.</p> </li> <li><p>The example uses good old <code>XMLHttpRequest</code>. You may want to try the more modern <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch" rel="nofollow noreferrer">fetch API</a> instead:</p> <pre class="lang-js prettyprint-override"><code>setInterval(function() { fetch(&quot;/temperature&quot;) .then(response =&gt; response.json()) .then(data =&gt; { data_field.innerText = data; }); }, 1000); </code></pre> </li> <li><p>If you are sending updates frequently enough to significantly load your Arduino, you may want to look at <a href="https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events" rel="nofollow noreferrer">Server-sent events</a>. This is a technique that allows you to significantly reduce the overhead of sending data updates. It is not as popular as Web-sockets, but has the advantage of being simpler to implement server-side.</p> </li> <li><p>If you can put a reverse-proxy between your Arduino and the Internet, the proxy can handle the static content. Your Arduino then only handles the dynamic data and wouldn't need an SD card. If you reverse-proxy Server-sent events, make sure the proxy doesn't buffer the server response. See for example these <a href="https://stackoverflow.com/questions/13672743/eventsource-server-sent-events-through-nginx">tips on configuring Nginx</a> for this purpose.</p> </li> <li><p>The static data could also be served from a completely different Web site. For this to work, you have to fulfill two conditions:</p> <ol> <li><p>The Arduino server has to add the header <code>Access-Control-Allow-Origin: *</code> to its responses.</p> </li> <li><p>On the client code, you have to provide the full URL of the Arduino as an argument of <code>request.open()</code>, <code>fetch()</code> or <code>new EventSource()</code>.</p> </li> </ol> </li> <li><p>The previous trick also allows you to open the Web page directly from your local file system, which can be very handy for developing.</p> </li> <li><p>Once you get the basic scheme working, Web technologies allow you to get as fancy as you want. You could create an analogue gauge (with SVG transform rotate). You could even <a href="https://plotly.com/javascript/" rel="nofollow noreferrer">add a graph</a>, updated in real time, that shows the time evolution of the temperature, and is entirely handled by the client.</p> </li> </ul>
89486
|arduino-uno|
Arduino compiler shows different value of sram memory
2022-04-28T02:39:54.120
<p>I have this code that shows the available sram memory</p> <pre><code> int freeRam() { extern int __heap_start, *__brkval; int v; return (int) &amp;v - (__brkval == 0 ? (int) &amp;__heap_start : (int) __brkval); } void setup() { Serial.begin(9600); Serial.println(freeRam()); } void loop() { } </code></pre> <p><a href="https://i.stack.imgur.com/AY4l3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AY4l3.jpg" alt="enter image description here" /></a></p> <p>The arduino compiler shows a different value.</p> <ul> <li>the arduino compiler shows 1856 bytes and</li> <li>Serial port shows 1850 bytes</li> </ul> <p>What is the correct value?</p>
<p>Both are correct depending on what value you are interested in. The compiler tells you the size of the global variables. Your code tells you how much memory is free at any one time. Running code requires memory (most often the stack growing to accommodate local variables and the &quot;stack frame&quot; with a copy of the CPU registers in it every time you call a function).</p> <p>In other words the compiler tells you how much is in your glass when it's handed to you by the barman but your code tells you how much is in there once you have taken a sip.</p>
89488
|usb|esp32|
My ESP32-S3 DevkitC-1 has two USB micro ports labeled 'USB' and 'UART'. What are they for?
2022-04-28T03:17:12.163
<p>I'm new to micro-controllers. I've got an ESP32-S3-DevKitC-1 and I'm trying to do a simple hello world with the Serial. I'm using the Arduino IDE for flashing and serial monitoring. My code is:</p> <pre><code>/** * As simple as it gets, right? Setup the Serial, wait on it. The periodically print during the loop. */ void setup() { Serial.begin(9600); // Initialize serial communications with the PC while (!Serial); } void loop() { Serial.println(&quot;Hello World&quot;); delay(1000); } </code></pre> <p>I've tried various baud rates. I've also tried a few different configurations for flashing-- this includes flashing over the UART port with upload mode 'UART0/Hardware CDC' and 'USB-OTG CDC (TinyUSB)'. I'm basically at guess and check right now and am looking for some tips or resources to understand the ports. My serial always shows gibberish. I've even tried miniterm like this:</p> <p><code>pyserial-miniterm /dev/cu.usbserial-1410 9600</code></p>
<p>I had to spent some additional time debugging my smart hardware electronics for a home automation wall mount switch based on the ESP32 S3 ( see it on my GitHub <a href="https://github.com/aeonSolutions/AeonLabs-Smart-Power-Switch-Outlet/blob/main/README.md" rel="nofollow noreferrer">here</a> )</p> <p><a href="https://i.stack.imgur.com/wACFh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wACFh.png" alt="enter image description here" /></a></p> <p>because I was able to upload the firmware code into it however when reading serial output it only displayed &quot;gibberish&quot; characters.</p> <p>On the internet I could not find the answer, so I had to work harder to find the solution. Common problems found when dealing with serial output errors are:</p> <ul> <li>poor UART ground</li> <li>absence of a 500 Ohm resistor on the TX line</li> <li>UART cable to long</li> <li>track coupling and track length mismatch</li> </ul> <p>are all hardware issues that cause serial communication errors and malfunctioning. However, for the ESP32 there's one missing on the list above. On this particular hardware, I had incorrectly soldered the RTC crystal of 32,768MHz into the MCU crystal place which is for one of 40MHz. The result was, it is possible to do firmware upload using a 32,768Mhz crystal for the MCU however, and due to the incorrect clock frequency, serial output is no longer 115200bps and displays &quot;gibberish&quot; characters.</p> <p><strong>In summary make sure the crystal has the correct clock frequency value</strong>.</p>
89496
|esp32|security|
ESP32 Wipe Sensitive Key Data
2022-04-28T12:56:27.827
<p>Is it possible to ensure that keys (e.g. ssid, ssl certs) are wiped from the memory of a esp32?</p> <p>I'm new to the esp32, coming from a IoT device security perspective.</p> <p>Say a person was testing an esp32 application that utilized WIFI, in which sensitive keys are embedded in the firmware. They then overwrote the esp32 with a small led blink firmware in an attempt to clear said keys.</p> <p>I would like to know if flashing a small &quot;blink&quot; program will be sufficient to remove the keys, so the esp32 could be repurposed without worry that a firmware dump would reveal past firmware information.</p> <p>This question is specifically targeting scenarios where the esp32 is for development purposes (fuse bits are never burnt - mind I think there is a security flaw where chip can be dumped anyhow).</p>
<p>You can use <code>esptool.py</code> to run an <code>erase_flash</code> operation.</p> <blockquote> <p><strong>Erase Flash: erase_flash &amp; erase_region</strong></p> <p>To erase the entire flash chip (all data replaced with 0xFF bytes):</p> <pre><code>esptool erase_flash </code></pre> <p>To erase a region of the flash, starting at address 0x20000 with length 0x4000 bytes (16KB):</p> <p>esptool erase_region 0x20000 0x4000</p> <p>The address and length must both be multiples of the SPI flash erase sector size. This is 0x1000 (4096) bytes for supported flash chips.</p> <p><em>-- <a href="https://docs.espressif.com/projects/esptool/en/latest/esp32s3/esptool/basic-commands.html" rel="nofollow noreferrer">esptool basic commands</a></em></p> </blockquote> <p>As far as copy protection goes you can encrypt the flash contents so even if the chip is read directly without the decryption key they won't be able to make any sense of the data.</p>
89519
|timers|time|
How to efficiently code a long duration timer
2022-05-01T13:05:08.043
<p>I'm working on a battery-powered project. I'm trying to write code, which checks the battery voltage every 30 minutes and changes the color of a LED accordingly. Should I still be using <code>millis()</code> or is there a more efficient way to create a timer which tracks these longer time periods? Should I be concerned that the value of millis resets every 50 days, with an example timer like this:</p> <pre><code>bool timer(unsigned long &amp;last_time, unsigned long period) { unsigned long now = millis(); if (now - last_time &gt;= period) { last_time = now; return true; } return false; } </code></pre>
<p>A library I like for this kind of task is Ticker</p> <pre><code>#include &lt;Ticker.h&gt; void batterycheck() { // called by battcheck ticker every 30 minutes // read_voltage... // set_led_color... } Ticker battcheck(batterycheck, 30*60*1000, 0); setup() { battcheck.start(); } loop() { battcheck.update(); } </code></pre> <p>There's no advantage over doing it manually but I found this library after writing almost exactly the same code for a project that had a bunch of timers running concurrently.</p>
89532
|serial|communication|
How to use Sim7020_mini NB-IOT module
2022-05-02T11:33:24.153
<blockquote> <p>I bough Sim7020_mini module. I put IOT Sim card, and plug-in antenna, connect Rx,Tx into USB-TTL, then put supply into VIN (5 volt), LED power was lid on. Arduino Serial Monitor set into 115200, but no character appear, also I enter AT, no answer. I already making sure my wiring. Measuring STATUS pin 42 showing 1.8 volt, means not active.</p> <p>Schematic look like wrong, according to sim7020 Hardware design v1.02, to put SIM7020 to On we should give LOW pulse 1 second into PWRKEY. But STATUS pin still 1.8 volt.</p> <p>May anyone has successful using this such module? Any clue?</p> </blockquote> <p><a href="https://stackoverflow.com/questions/72073576">First question about using SIM7020_mini Module</a></p> <p>Thank you @hcheung for clue about 1.8 volt.</p> <p>The SIM7020_mini module already equipped with logic level shifter between 1.8v and 3.3v.</p> <p>I know SIM 7020C already Up, pin <code>STATUS</code> (42) is HIGH, pin <code>NETLIGHT</code> (41) blinking.</p> <p>Here is my schematic, I just want to enter AT Command first. But on my Serial Monitor (Arduino) doesn't show any character received.</p> <p><img src="https://i.stack.imgur.com/CADEM.png" alt="schematic" /></p> <p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fCADEM.png">simulate this circuit</a> &ndash; Schematic created using <a href="https://www.circuitlab.com/" rel="nofollow">CircuitLab</a></sup></p> <p>When I type 'AT' it's echoed back to screen Serial Monitor. When I reverse Tx/Rx between SIM7020_mini module and USB-TTL, no character echoed. When I restart SIM7020_mini module, there is no character received by Serial Monitor.</p>
<p>My fault, AT command on Serial Monitor (Arduino IDE) should be ending with <code>Carriage Return</code>, while my Serial Monitor using <code>New Line</code></p> <p>Thank you for responses.</p>
89534
|arduino-mega|c++|stepper-motor|
Using a 5 pin button with Arduino Correctly
2022-05-02T13:28:01.483
<p>I am trying to build a simple motor test sketch, currently, to test a NEMA 23 stepper motor and the DM542T stepper driver.</p> <p>Here is the code, and I am having trouble figuring out how to properly wire the 5-lead button (+, -, Common, NO, NC)</p> <p>Here is the code</p> <pre><code>// Pin numbers const int buttonPin = 2; const int directionPin = 8; const int stepPin = 9; // Other constants const int NumSteps = 5000; // steps const int Speed = 500; void setup() { pinMode(buttonPin, INPUT_PULLUP); pinMode(directionPin, OUTPUT); pinMode(stepPin, OUTPUT); digitalWrite(directionPin, LOW); digitalWrite(stepPin, LOW); } void loop() { if (digitalRead(buttonPin)) { // Move in one direction for (int distance = 0; distance &lt; NumSteps; distance++) { digitalWrite(stepPin, HIGH); delayMicroseconds(Speed); digitalWrite(stepPin, LOW); delayMicroseconds(Speed); } // Reverse direction digitalWrite(directionPin, !digitalRead(directionPin)); } delay(5); } </code></pre> <p>The button is a momentary button, so I am holding it in to simulate a latching button.</p> <p>I have the buttons Common and Neg leads wired together, and connected to the Gnd pin on the Arduino (mega rev3) I have the buttons Positive and the NC wired together and connected to pin 2.</p> <p>Wiring that button in that manner, works fine in the button-controlled blink sketch, but is not working here (LED on the button doesn't light up and the motor test doesn't run).</p> <p>Note: I am using a 5 lead momentary button as that what the project these motors will be for will be using.</p> <p>Any help appreciated.</p>
<p>The button's pins are as follows:</p> <ul> <li>+: The LED's anode</li> <li>-: The LED's cathode</li> <li>C: The common pin of the switch</li> <li>NC: Normally Closed - is normally connected to the C pin until the button is pressed</li> <li>NO: Normally Open - is connected to the C pin when you press the button</li> </ul> <p>So to use the button as a button the two pins you care about are C and NO. Use those pins (in any order) as you would any normal button with a pullup resistor (or the internal <code>INPUT_PULLUP</code> resistor).</p> <p>To use the LED can be a little more tricky. Most of this style of button have the LED set up for 12V usage. While you <em>may</em> get a slight glow from it from 5V you would probably need to switch it with a transistor and power it from 12V to get it to light up properly. However your button may be rated differently and need a different voltage.</p>
89553
|c++|esp32|eeprom|
What is wrong with the way I write and or read the EEPROM adresses?
2022-05-06T10:01:15.877
<p>Consider:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;EEPROM.h&gt; byte guifactor1 = 1; byte guifactor2 = 2; byte guifactor3 = 3; byte guifactor4 = 4; byte guifactorgas = 5; byte guifactorwater = 6; volatile unsigned long count1factor; volatile unsigned long count2factor; volatile unsigned long count3factor; volatile unsigned long count4factor; volatile unsigned long countgasfactor; volatile unsigned long countwaterfactor; void loop(){ if (guifactor1 &gt; -1){ EEPROM.write(1, guifactor1); EEPROM.commit(); count1factor = EEPROM.read(1); Serial.println(count1factor); } if (guifactor2 &gt; -1){ EEPROM.write(2, guifactor2); EEPROM.commit(); count2factor = EEPROM.read(2); Serial.println(count2factor); } if (guifactor3 &gt; -1){ EEPROM.write(3, guifactor3); EEPROM.commit(); count3factor = EEPROM.read(3); Serial.println(count3factor); } if (guifactor4 &gt; -1){ EEPROM.write(4, guifactor4); EEPROM.commit(); count4factor = EEPROM.read(4); Serial.println(count4factor); } if (guifactorgas &gt; -1){ EEPROM.write(5, guifactorgas); EEPROM.commit(); countgasfactor = EEPROM.read(5); Serial.println(countgasfactor); } if (guifactor1 &gt; -1){ EEPROM.write(6, guifactorwater); EEPROM.commit(); countwaterfactor = EEPROM.read(6); Serial.println(countwaterfactor); } } void setup(){ } </code></pre> <p>The problem I have with my code is that it either doesn’t write the value to the EEPROM or it doesn’t read the value as it doesn’t print anything to the monitor.</p> <p>I expected to read 1 2 3 4 5 6 from the monitor as I write the bytes to the EEPROM and then transfer the value to the <em>unsigned long</em> and print the variable.</p>
<p>You forgot to call <code>Serial.begin()</code> in <code>setup()</code>.</p> <p>As a side note, your <code>if</code> tests are useless. The compiler warns me that:</p> <pre><code>comparison is always true due to limited range of data type </code></pre> <p><strong>For reference</strong>: the previous answer, valid for the initial question where <code>guifactor1</code> and co. were all <code>unsigned long</code>.</p> <hr /> <p>The program does nothing because all the actions are conditioned on tests such as</p> <pre class="lang-cpp prettyprint-override"><code>if (guifactor1 &gt; -1) </code></pre> <p>and these tests are always false. The reason they are false is because arithmetic comparison operators such as <code>&lt;</code> <a href="https://en.cppreference.com/w/cpp/language/operator_comparison#Arithmetic_comparison_operators" rel="nofollow noreferrer">perform <em>usual arithmetic conversions</em></a> on their operands prior to doing the actual comparison. Since <code>guifactor1</code> is <code>unsigned long</code>, and this type has a higher conversion rank than <code>int</code> (the type of <code>-1</code>), the second operand is implicitly converted to <code>unsigned long</code>, yielding <code>ULONG_MAX</code>.</p>
89555
|serial|arduino-mega|python|
Sending float values from Python to Arduino using Serial communication
2022-05-06T11:19:34.340
<p>I need to send an array of floating-point numbers from python to Arduino Mega. For that, I read many sources<a href="https://arduino.stackexchange.com/questions/49682/sending-float-values-from-python-to-arduino-via-serial-communication"> [this</a> <a href="https://arduino.stackexchange.com/questions/5090/sending-a-floating-point-number-from-python-to-arduino">this</a> <a href="https://arduino.stackexchange.com/questions/45874/arduino-serial-communication-with-python-sending-an-array">this</a> <a href="https://stackoverflow.com/questions/27639605/send-a-list-of-data-from-python-to-arduino-using-pyserial">this</a> <a href="https://arduino.stackexchange.com/questions/9627/send-multiple-int-values-from-python-to-arduino-using-pyserial">this]</a> <a href="https://forum.arduino.cc/t/sending-float-values-from-python-to-arduino-via-serial-stumped/455736" rel="nofollow noreferrer">this</a>] and many more links for the same I referred. But unable to solve the problem.</p> <p>I tried to send the angles to Arduino through python and return these values to python to print.</p> <p>Below is the Python code in which I try to send the array named angle and tries to print the values received from Arduino.</p> <pre><code>import cv2 import numpy as np import serial import struct import time ser = serial.Serial('COM3', 9600, timeout = 1) time.sleep(2) if(ser.isOpen() == False): ser.open() print('com3 is open', ser.isOpen()) angle = [120.2,154.2,14.25] ser.write(struct.pack('&gt;fff', 10.5,11.9,48.2)) # B for interger and f for float #ser.write(struct.pack('&gt;f', angle)) # B for interger and f for float time.sleep(2) ser.flush() data = ser.readline() data = str(data.decode(&quot;utf&quot;)) print(data) ser.close() </code></pre> <p>Below is the Arduino code:</p> <pre><code>float f1; float f2; float f3; void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println(&quot;Arduino is in parseFloat!&quot;); } void loop() { if (Serial.available() &gt; 0) { d1 = Serial.parseFloat(); d2 = Serial.parseFloat(); d3 = Serial.parseFloat(); ad = d1 +2.5; Serial.println(ad) } delay(2000); } </code></pre> <p>The error I got is: I got no error or warnings but there is no output also for the print commands as shown in below Figure. <a href="https://i.stack.imgur.com/eKuND.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eKuND.png" alt="enter image description here" /></a></p> <p>I need help to send the values to Arduino using python.</p>
<p>There are two things going on here.</p> <p><strong>First</strong> of all, if you look up the <a href="https://docs.python.org/3/library/io.html#io.IOBase.readline" rel="nofollow noreferrer"><em>readline()</em> method in Python</a> that is referenced in the <a href="https://pyserial.readthedocs.io/en/latest/pyserial_api.html" rel="nofollow noreferrer">PySerial manual</a>, you'll see the following:</p> <pre><code>readline(size=- 1, /) Read and return one line from the stream. If size is specified, at most size bytes will be read. The line terminator is always b'\n' for binary files; for text files, the newline argument to open() can be used to select the line terminator(s) recognized. </code></pre> <p>In your program, you are actually sending more than one line back to serial port from the Arduino. The first line is the ASCII-encoded &quot;Arduino is in ParseFloat!&quot;. The second one is the test float calculation. If you don't account for the fact you are expecting multiple &quot;lines&quot; from the serial port, you wouldn't see the test calculation, because you are not actually reading it. For encoded data, it states that the line ends at the '\n' char/digit (10).</p> <p><strong>Try it out</strong> change the &quot;println&quot; to &quot;print&quot; in your Arduino program and add another message either in the setup or the loop. Run your Python program. What do you see? Now change the &quot;print&quot; back to println&quot;. Run your Python program again. What do you see now?</p> <p><strong>Secondly</strong>, Edgar Bonet points out the second issue. The <em>write()</em> method in the PySerial API requires data to be a bytes array, but it's the way you are encoding it. It seems that the Arduino Serial class expects a ASCII-encoded byte-array, rather than a float byte-array (the floats encoded as a single-precision floating point number), which is what you are sending.</p> <p>If you change your code to something like this (for example):</p> <pre><code>angle = [120.2,154.2,14.25] ser.write(str(angle).encode('utf-8')) </code></pre> <p>you should be able to see your test calculation come back, granted that you read what I wrote in the first part of this answer.</p>
89556
|serial|nodemcu|ubuntu|
Ubuntu Serial Port Briefly showing on arduino IDE
2022-05-06T12:56:37.517
<p>I am using a NodeMcu with Arduino IDE on Ubuntu. I have managed to upload the blink script and it work. Now, when i plug the nodemcu, the serial port /dev/ttyUSB0 is briefly available in the IDE. After 2 seconds, the port menu is grayed out again and I can't use it.</p> <p>Same with <code>ls /dev/tty*</code> <code>/dev/ttyUSB0</code> is briefly available.</p> <pre class="lang-bash prettyprint-override"><code>/dev/tty /dev/tty23 /dev/tty39 /dev/tty54 /dev/ttyS10 /dev/ttyS26 /dev/tty0 /dev/tty24 /dev/tty4 /dev/tty55 /dev/ttyS11 /dev/ttyS27 /dev/tty1 /dev/tty25 /dev/tty40 /dev/tty56 /dev/ttyS12 /dev/ttyS28 /dev/tty10 /dev/tty26 /dev/tty41 /dev/tty57 /dev/ttyS13 /dev/ttyS29 /dev/tty11 /dev/tty27 /dev/tty42 /dev/tty58 /dev/ttyS14 /dev/ttyS3 /dev/tty12 /dev/tty28 /dev/tty43 /dev/tty59 /dev/ttyS15 /dev/ttyS30 /dev/tty13 /dev/tty29 /dev/tty44 /dev/tty6 /dev/ttyS16 /dev/ttyS31 /dev/tty14 /dev/tty3 /dev/tty45 /dev/tty60 /dev/ttyS17 /dev/ttyS4 /dev/tty15 /dev/tty30 /dev/tty46 /dev/tty61 /dev/ttyS18 /dev/ttyS5 /dev/tty16 /dev/tty31 /dev/tty47 /dev/tty62 /dev/ttyS19 /dev/ttyS6 /dev/tty17 /dev/tty32 /dev/tty48 /dev/tty63 /dev/ttyS2 /dev/ttyS7 /dev/tty18 /dev/tty33 /dev/tty49 /dev/tty7 /dev/ttyS20 /dev/ttyS8 /dev/tty19 /dev/tty34 /dev/tty5 /dev/tty8 /dev/ttyS21 /dev/ttyS9 /dev/tty2 /dev/tty35 /dev/tty50 /dev/tty9 /dev/ttyS22 /dev/ttyUSB0 /dev/tty20 /dev/tty36 /dev/tty51 /dev/ttyprintk /dev/ttyS23 /dev/tty21 /dev/tty37 /dev/tty52 /dev/ttyS0 /dev/ttyS24 /dev/tty22 /dev/tty38 /dev/tty53 /dev/ttyS1 /dev/ttyS25 </code></pre> <p>After 2 seconds:</p> <pre class="lang-bash prettyprint-override"><code>/dev/tty /dev/tty23 /dev/tty39 /dev/tty54 /dev/ttyS10 /dev/ttyS26 /dev/tty0 /dev/tty24 /dev/tty4 /dev/tty55 /dev/ttyS11 /dev/ttyS27 /dev/tty1 /dev/tty25 /dev/tty40 /dev/tty56 /dev/ttyS12 /dev/ttyS28 /dev/tty10 /dev/tty26 /dev/tty41 /dev/tty57 /dev/ttyS13 /dev/ttyS29 /dev/tty11 /dev/tty27 /dev/tty42 /dev/tty58 /dev/ttyS14 /dev/ttyS3 /dev/tty12 /dev/tty28 /dev/tty43 /dev/tty59 /dev/ttyS15 /dev/ttyS30 /dev/tty13 /dev/tty29 /dev/tty44 /dev/tty6 /dev/ttyS16 /dev/ttyS31 /dev/tty14 /dev/tty3 /dev/tty45 /dev/tty60 /dev/ttyS17 /dev/ttyS4 /dev/tty15 /dev/tty30 /dev/tty46 /dev/tty61 /dev/ttyS18 /dev/ttyS5 /dev/tty16 /dev/tty31 /dev/tty47 /dev/tty62 /dev/ttyS19 /dev/ttyS6 /dev/tty17 /dev/tty32 /dev/tty48 /dev/tty63 /dev/ttyS2 /dev/ttyS7 /dev/tty18 /dev/tty33 /dev/tty49 /dev/tty7 /dev/ttyS20 /dev/ttyS8 /dev/tty19 /dev/tty34 /dev/tty5 /dev/tty8 /dev/ttyS21 /dev/ttyS9 /dev/tty2 /dev/tty35 /dev/tty50 /dev/tty9 /dev/ttyS22 /dev/tty20 /dev/tty36 /dev/tty51 /dev/ttyprintk /dev/ttyS23 /dev/tty21 /dev/tty37 /dev/tty52 /dev/ttyS0 /dev/ttyS24 /dev/tty22 /dev/tty38 /dev/tty53 /dev/ttyS1 /dev/ttyS25 </code></pre> <p>How can I fix that? I have try all the usb ports. The NodeMCU settings: <a href="https://i.stack.imgur.com/MgBNg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MgBNg.png" alt="enter image description here" /></a></p> <p>Actually Using Ubuntu 22.04 LTS</p> <p>EDIT: While running <code>sudo dmesg -w</code> and connecting the mcu I get:</p> <pre><code>[ 3726.038486] usb 1-1: new full-speed USB device number 13 using xhci_hcd [ 3726.220532] usb 1-1: New USB device found, idVendor=10c4, idProduct=ea60, bcdDevice= 1.00 [ 3726.220536] usb 1-1: New USB device strings: Mfr=1, Product=2, SerialNumber=3 [ 3726.220537] usb 1-1: Product: CP2102 USB to UART Bridge Controller [ 3726.220538] usb 1-1: Manufacturer: Silicon Labs [ 3726.220539] usb 1-1: SerialNumber: 0001 [ 3726.229998] cp210x 1-1:1.0: cp210x converter detected [ 3726.231005] usb 1-1: cp210x converter now attached to ttyUSB0 [ 3727.565688] usb 1-1: usbfs: interface 0 claimed by cp210x while 'brltty' sets config #1 [ 3727.566375] cp210x ttyUSB0: cp210x converter now disconnected from ttyUSB0 [ 3727.566391] cp210x 1-1:1.0: device disconnected </code></pre>
<p>This could be happening because <code>Brltty</code> application. Remove it and try again.</p> <pre><code>sudo apt remove brltty sudo apt autoclean &amp;&amp; sudo apt autoremove </code></pre>
89558
|arduino-uno|simulator|
Why the led is always on in proteus?
2022-05-07T09:44:20.137
<p>I am simulating a circuit with arduino, which determine if there is current at input, then turn the led on at the output. The problem is the light is always on even when the button is open at the input.</p> <p><a href="https://i.stack.imgur.com/B6n2x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B6n2x.png" alt="enter image description here" /></a></p> <p>This is my code:</p> <pre><code>void setup() { pinMode(7, OUTPUT); pinMode(8, INPUT); digitalWrite(7, LOW); } void loop() { int on = digitalRead(8); digitalWrite(7, on); } </code></pre> <p>Why does this happen and how do I solve it?</p> <p>Any help would be appreciated.</p>
<p>Microcontroller inputs don't detect the presence of current. They compare a voltage to a threshold.</p> <p>In reality the input pin is closest to a capacitor. You press your button and it charges that capacitor to above the threshold voltage for &quot;HIGH&quot;. Then you release the button but that capacitor remains charged and still reading &quot;HIGH&quot;. You need something to reduce the charge on that capacitor to below the &quot;LOW&quot; threshold voltage.</p> <p>This is most normally done with a resistor between the GPIO pin and GND which will &quot;bleed off&quot; that charge and give you a LOW reading when the button is released.</p> <p>This is a &quot;pull down&quot; resistor (you can also reverse it and have a &quot;pull up&quot; resistor and the button connected to GND) and is an essential part of any input that doesn't itself generate both the HIGH and LOW voltages required (any switch or button).</p> <p>Also 10V on a GPIO pin <strong>will</strong> destroy your Arduino.</p>
89561
|shields|battery|atmega2560|solar|charging|
Arduino + Solar Charger Shield V2.2: Battery and Solar panels selection
2022-05-07T12:57:21.230
<p>first of all I would like to apologize for the, probably very basic and stupid questions for you, but I'm not an electronic expert..</p> <p>I'm implementing my project using an Arduino Mega 2560 (I need more pins.. this is the most important reason that it drives the Arduino choice) I'll put my project in an external environment without the electricity source. For this reason my idea is to use a battery with a solar panel as power input to charge the battery. I also applied some low-power techniques in order to reduce energy consumption as much as possible. Regarding the solar panel and battery connections I purchased this Arduino Solar Shield.</p> <p><a href="https://wiki.seeedstudio.com/Solar_Charger_Shield_V2.2/" rel="nofollow noreferrer">Solar Charger Shield V2.2 - Seeed Wiki</a></p> <p>And here I'm a bit (a lot) confused about the choice of the battery and the solar panel(s) to be purchased. First of all, my idea is to use multiple (2 or 4) solar panels in order to exploit as much as possible the solar light (multiple positions) but I'm not able (I'm not sure) about the solar panel selection to purchase. Considering that the maximum current that the solar shield could be delivered is 700mA can I use 4 solar panels like this <a href="https://www.seeedstudio.com/1W-Solar-Panel-80X100.html" rel="nofollow noreferrer">https://www.seeedstudio.com/1W-Solar-Panel-80X100.html</a> (applying also 4 applying 4 diodes to avoid reverse current)?</p> <p>About this the possible number or size of the solar panels Do I need to consider the amount of th Current at Peak Power? For example, using 4 solar panels with 170mA as Current at Peak Power, 4*170 = 680 that it's &gt; of the current of the solar shield. So, is this wrong? Do I reduce the amount of the panels or do I use a different panel?</p> <p>About the Solar input voltage it's 4.8~6V. These are the specifications about the solar panel:</p> <p>Dimensions: 100x80x2.5(±0.2) mm Typical voltage: 5.5V Typical current: 170mA Open-circuit voltage: 8.2 V Maximum load voltage: 6.4V Maximum load voltage, Open-circuit voltage are &gt; Solar input voltage. Is it a risk? About the lipo battery, can I use a battery 3.7v and about the mAh value as high as possible (for example this <a href="https://www.amazon.it/2100mAh-Lithium-Polymer-Replacement-Bluetooth/dp/B095BTSMYH/?th=1" rel="nofollow noreferrer">https://www.amazon.it/2100mAh-Lithium-Polymer-Replacement-Bluetooth/dp/B095BTSMYH/?th=1</a> ?) What about the maximum current value (in this case 5A)? Is it ok? In case, can you suggest me something else?</p> <p>** *********** EDIT *********** **</p> <p>As suggested I'm updating my question in order to give additional info about my scenario.</p> <p>My project will be installed in an external environment (with some atmospheric protections IP67). The location, from solar irradiation point of view, it's a good place: <a href="https://globalsolaratlas.info/detail?m=site&amp;c=40.283716,17.586365,9&amp;a=18.056138,39.997805,18.056138,40.420456,18.535172,40.420456,18.535172,39.997805,18.056138,39.997805&amp;s=40.11799,18.382874" rel="nofollow noreferrer">https://globalsolaratlas.info/detail?m=site&amp;c=40.283716,17.586365,9&amp;a=18.056138,39.997805,18.056138,40.420456,18.535172,40.420456,18.535172,39.997805,18.056138,39.997805&amp;s=40.11799,18.382874</a></p> <p>About my project:</p> <ul> <li>I'll have to take the measurements from more sensors:</li> <li>starting from 1 to 10/15 humidity/temperature (DHT22) sensor;</li> <li>starting from 1 to 10/15 load cells (4 load cells for each HX711);</li> <li>I'll send the data using some transmissions using a LORA Shield.</li> </ul> <p>I don't need to retrieve the measurements continuously or in very short periods.</p> <p>The idea is to sleep my Arduino (in low power with all power sensors disconnected) and, using a RTC DS3231 module, to wake-up it on regular intervals, read the data, send it via LORA and go to sleep again.</p> <p>The idea is to wake-up every 15 minutes. The time that I imagine about the measurements and the send will take a few seconds (around 30s in case I can approximate it to 1 minute).</p> <p>And at the moment I don't have the exact measurements about the used current (because I can connect all here.. but I need to purchase the solar panels and the battery in order to make a real test also)..So, the idea now is to approximate.. In case I can adjust something later.</p> <p>At the moment, measuring the current I have.</p> <p>around 0.35mA when the Arduino is sleeping.</p> <p>I probably can reduce it again because I have to remove 2 power led indicators (1 on my DS3231, one on my LORA shield... and, in case, also the power led on my Arduino).</p> <p>When the Arduino works (live mode) probably I can consider around 90/100mA (probably this is too much) for 30s).</p> <p>I'm not expert but, using this values I calculated the average about the used current in 1 hour:</p> <p>((100mA * 4 minutes) + (0,35mA * 56 minutes)) /60 = 7mA/m 420 mA/h</p> <p>I'll need 5v about the voltage.</p> <p>I don't have any limitation about the size or the space.</p> <p>I think that considering 7days without solar power supply or bad water conditions could be enough (in my opinion it's too much)</p>
<p>This is a question that's better suited for the electrical engineering SO, but I can give you some pointers to reword and re-post your question so it's not as broad.</p> <p>Right now you have a few unknown variables to juggle, so you should be jotting down your thoughts on all of the following:</p> <ul> <li>Where will the unit be placed and/or located? How long do you expect it to go without needing to have its battery recharged?</li> <li>What is the continuous power consumption? You should know your approximate continuous current consumption and at which voltage you will be running the Arduino and the sensors that you connect to it</li> <li>What environmental conditions do you expect the unit to experience? Do you have a limiting factor on size or space?</li> <li>How much are you willing to pay?</li> </ul> <p>You can definitely use multiple solar panels, but you'd have to connect them in parallel (so they maintain the same voltage), and even then, the linked charger shield can only go up to 900 mA of charging current. The 600-700 mA is the supported power output of the battery, or the max current that the shield can provide to your system thru the shield. It can be larger if you lower the system's voltage and stay within the maximum limits of the charger shield.</p> <p>With regards to your second question, yes, current at peak power is a good metric for your approximations. If you go thru my questions, you will know how much your systems consumes in a day and choose a battery that can discharge no more than X amount of percent per day (depending on the type of battery). Your goal is to be able to charge that battery back at least close to its full capacity--your solar panels or the amount of thereof, as well as your charger, will be dictated by that.</p> <p>For the Voc of the solar panel - ideally, it would be less than the solar input voltage. It's the voltage of the panel without a load connected to it. Of course, you will have a load connected to the solar panel and thus the typical voltage will be around what's stated, but if you don't want to damage your charger, you have to make sure your SP will be properly loaded under most conditions! It will be safer to connect multiple smaller SPs to get the current that will keep the system up and charge your battery.</p> <p>With regards to the battery current - you have to check which current it is. Is it the charging current? Output current? Be mindful that you are limited by your charger in this case (3W output, 900 mA charging current).</p> <p>Hope this gives you a start! It's a good question, but you need to do some more reading and you need to have a better idea of the design for your system before we can be more helpful.</p> <p>Edit:</p> <p>Per the updated information...</p> <p>I will use your estimates, but do consider that for sensors that require power, you can add them and make your calculations more accurate. Also, while LoRA is low-power, it will consume some power too, and you can factor that in.</p> <p>Let's assume your numbers are correct and the average current consumption averages out to ~ 420 mA/h. Then, if you want to keep the system alive for 7 days, you'll need a battery with a capacity of 420 mA/h * 24 hours/day * 7 days -&gt; 70,560 mAh or 70.560 Ah. At 5 volts, your system effectively requires 0.420 A/h * 5 V -&gt; 2.1 Watts/hour (finicky units here, eh?). That would translate to ~353 Watts/week. Also, 5V means you will need a battery that can provide that voltage - a lower voltage battery will not support your system.</p> <p>The next thing you have to consider then is the battery type - <a href="https://batterysolutions.com/learning-center/battery-types/" rel="nofollow noreferrer">there are a few</a>, but the ones I'd go for are either Li-ion or VRLA (valve-regulated lead acid). There is a tradeoff between cost - Li-ion batteries cost more, but they are typically better in the majority of factors rather than SLA (sealed lead acid) batteries. Doing some googling, you could get a 70-100 Ah SLA/VRLA for ~$200-300 and a Li-ion for ~$400-500. Do note, however, that you can discharge Li-ion batteries more deeply than VRLA ones - it's recommended to keep the charge on the VRLA batteries around ~50% and preferably around ~75% to extend its life. You can discharge Li-ion batteries up to 80% or a bit more and that's fine, they don't suffer as extensive reduction in their lifetime like SLAs.</p> <p>To put that into perspective, if you have an application that requires ~8 Ah, then ideally for a VRLA you'd need to size a battery such that it doesn't go below 50% for your worst-case application scenario. That is, if you think you'll need the device to run for 7 days without any sun, then you'll need a battery of a 16 Ah capacity or more. Even bigger if you want to extend its lifetime. For Li-ion, aiming at a bit higher than 8 Ah should be fine. For your application, that means getting a SLA battery that's &gt; 140 Ah (unless it's a deep discharge SLA battery) or a Li-ion battery that's close to 70 Ah.</p> <p>Now, it must be noted that most batteries that provide those capacities typically come in 12V, so you would have to add a buck-converter to convert from 12V to the battery voltage your charger needs (3-4.5V). The charger you linked states that it can provide up to 3W out, which is 600 mA max at 5V. That would support your application as your average current draw is less than 600 mA.</p> <p>For charging, however, you have to keep in mind that your system, on average, draws 420 mA/hour. So the charger's charging capabilities would actually be 900 - 420 -&gt; 480 mA/hour. That means that based on worst-case considered direct solar irradiation hourly data in the link you provided, you'd get ~ 8 hours of direct sunlight (again, worst case!). So 8 hours you can charge -&gt; 480 * 8 = 3840 mAh and you'll lose 6720 (420 * 16) mAh. That is not good, because you're losing the charge on the battery each day.</p> <p>That means 2 things - you have to get a charger that permits a larger charging current within the maximum charging current of the battery rating AND you have to get enough panels (OR a big enough panel) to be able to provide that current. With the panels that you linked, the max current per panel is ~170 mA for the typical voltage of 5.5V. To provide a charging current of ~ 900 mA, you'd need 5 panels, but as mentioned above, that still wouldn't be enough. So, back to the drawing board...</p> <p>I hope this is enough to help you make more progress on your design.</p>
89566
|serial|
What is the default baud rate without calling Serial.begin?
2022-05-08T08:45:39.793
<p>I cannot find the answer from <a href="https://www.arduino.cc/reference/en/language/functions/communication/serial/begin/" rel="nofollow noreferrer">official document</a> and also surprised no one asked the same question.</p> <p>What is the default baud rates if I didn't call <code>Serial.begin</code>?</p>
<p>There is no default baud rate. When the sketch starts, the serial port is disabled (thus non-functional). Calling <code>Serial.begin()</code> enables the port.</p>
89568
|usb|arduino-leonardo|sleep|arduino-pro-micro|
Arduino Leonardo/Pro Micro sleep and USB
2022-05-08T09:07:58.693
<p>I am using an Arduino Pro Micro (basically a Leonardo in a smaller form factor) in a mobile application where power consumption is really important.</p> <p>To reduce power consumption, I put the Arduino to sleep, but that disconnects USB. That's not really acceptable in this application, since reconnecting USB after the Arduino wakes takes pretty long (a second or two).</p> <p>Is there some way to keep the USB connection alive while still conserving energy? E.g. by waking the ATMega32u4 frequently to keep the connection alive? Or is there some not-as-deep sleep moden where the USB connection stays alive?</p> <p>Edits for clarification:</p> <p>The device is an USB HID device. If the device goes to sleep after a few minutes of inactivity, having to reconnect after the user pressed a button causes quite a long delay between pressing the button and a reaction on the device.</p> <p>I am using the ATMega32u4's native USB implementation, so no V-USB or anything similar.</p> <p>I am putting the device to sleep like so:</p> <pre><code>Keyboard.end(); USBCON = 0; LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_OFF); </code></pre> <p>This is how I wake it up again:</p> <pre><code>USBDevice.attach(); delay(50); Keyboard.begin(KeyboardLayout_en_US); </code></pre>
<p>The Arduino has several sleep modes. They differ mainly by the clocks that are kept running, the peripherals that are enabled, and the possible wake-up sources. All these modes are described in the <a href="http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf#G5.998200" rel="nofollow noreferrer">datasheet of the ATmega32U4 microcontroller</a>, section 7: <em>Power Management and Sleep Modes</em>.</p> <p>You may see here that “Power-down” is one of the deepest sleep modes: all clocks are disabled, the main oscillator is turned off, and only asynchronous wake-up sources are available. As you have experienced, the USB port is not functional in this mode.</p> <p>In contrast, “Idle” is a somewhat shallow sleep: the CPU is halted but the peripherals remain clocked. Any enabled interrupt can be used as a wake-up source. This is a good option if you want the USB link to remain connected while sleeping, and you can get it with the <code>LowPower.idle()</code> function.</p> <p>If you are worried about the sleep mode to be too “shallow” and not save enough energy, note that the parameters if <code>LowPower.idle()</code> let you specify which peripherals you want to keep running during sleep. If you keep running only those that are needed, this should limit the power consumption to what is strictly needed.</p>
89572
|arduino-ide|ide|
Using a Microchip Fubarino with the Arduino IDE, how to acces and configure all pins
2022-05-08T19:18:13.083
<p>I recently got a Microchip Fubarino, contains a PIC32MX250F128D and I'm totally new to the Arduino IDE, i uploaded the blink sketch all fine and well. Schematic: <a href="https://ww1.microchip.com/downloads/en/DeviceDoc/FubarinoMini_v15_sch.pdf" rel="nofollow noreferrer">FubarinoMini_v15_sch</a></p> <pre><code>// the setup function runs once when you press reset or power the board void setup() { // initialize digital pin LED_BUILTIN as an output. //pinMode(LED_BUILTIN, OUTPUT); //asm (&quot;BSF PORTA,10&quot;); //pinMode(RA10, OUTPUT); //TRISA10 = 0; TRISAbits.RA10 = 0; //PORTAbits.RA10 = 1; //PORTAbits.RA10 = 0; // set to output //mapPps(20, PPS_OUT_SDO2) } // the loop function runs over and over again forever void loop() { //digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) PORTAbits.RA10 = 1; delay(500); // wait for a second //digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW PORTAbits.RA10 = 0; delay(500); // wait for a second } </code></pre> <p>restults in:</p> <pre><code> Blink:45:12: error: 'volatile union __LATAbits_t' has no member named 'RA10' LATAbits.RA10 = 0; </code></pre> <p>changing:</p> <pre><code>void loop() { //digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) PORTAbits.RA10 = 1; delay(500); // wait for a second //digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW PORTAbits.RA10 = 0; delay(500); // wait for a second } </code></pre> <p>doesn't work either.</p> <p>I also tried this example code: <a href="https://github.com/fubarino/fubarino.github.com/wiki/Fubarino-Mini-pps" rel="nofollow noreferrer">https://github.com/fubarino/fubarino.github.com/wiki/Fubarino-Mini-pps</a><br /> It does work.</p> <pre><code>#define LED 1 #define SCK2 4 #define SDI2 18 #define SDO2 20 </code></pre> <p>The led on the Fubarino board is not connected to pin 1, but to RA10. Pin 18 is the MCLR on the device, reviewing the datasheet you can't even set SDI2 &amp; SDO2 to the above defined numbers.</p> <p>Normally on a PIC16F84 or so, you would do something like this.</p> <pre><code>bank1 movlw b'00000001' movwf TRISA movlw b'11110000' movwf TRISB bank0 </code></pre> <p>the Arduino &quot;code&quot; seems a bit abstract. I Would like to experiment with the button.<br /> The Chipkit pps example shows you can use the Microchip keywords from the devices datasheet.</p> <p>Can the Fubarino be setup like a classic PIC device in the Arduino IDE? Configuring all the pins before going in to loop, using the Keywords from the datasheet.</p>
<p>The entries in the &quot;bits&quot; structures are named after the bits.</p> <p>It's not</p> <pre><code>TRISAbits.RA10 </code></pre> <p>but</p> <pre><code>TRISAbits.TRISA10 </code></pre> <p>The same goes for</p> <pre><code>LATAbits.LATA10 </code></pre> <p>The only exception is the &quot;port&quot; one</p> <pre><code>PORTAbits.RA10 </code></pre> <p>Which is a hangover from the old PIC16 chips that didn't have a LATx register.</p> <hr /> <blockquote> <p>The led on the Fubarino board is not connected to pin 1, but to RA10.</p> </blockquote> <p>Pin 1 is RA10. If you look in the file <code>Board_Data.c</code> for the Fubarino_Mini variant (<code>packages/chipKIT/hardware/pic32/2.1.0/variants/Fubarino_Mini/Board_Data.c</code>) you can see all the pin mappings. There's a bunch of arrays there that define how everything fits together.</p> <p>The second entry in most of those arrays (pin 1, starts counting at 0) is for RA10. As for</p> <blockquote> <p>Pin 18 is the MCLR on the device, reviewing the datasheet you can't even set SDI2 &amp; SDO2 to the above defined numbers.</p> </blockquote> <p>the PPS is a whole other mess on those chips. Pin 18 is not the 18th pin on the board, but digital IO pin number 18, which is the 19th entry in those pin array tables - RA4. Mapping RA4 is done through the file <code>packages/chipKIT/hardware/pic32/2.1.0/cores/pic32/pps/pingroups_1xx2xx.h</code> which contains an entry:</p> <pre><code>#define _PPS_RPA4 (2 + _PPS_SET_C) </code></pre> <p>and the file <code>packages/chipKIT/hardware/pic32/2.1.0/cores/pic32/pps/peripherals_1xx2xx.h</code> which has:</p> <pre><code>PPS_IN_SDI2 = (35 + _PPS_SET_C + _PPS_INPUT_BIT), </code></pre> <p>Those are then used by the mapPps() function to map RA4 to SDI2. Something which is perfectly possible.</p> <p>Yes, it's convoluted and a bit of a mess, but the best we could come up with given how limited the PIC32MX2xx IO multiplexer is.</p>
89604
|joystick|
Joystick reading erroneous values
2022-05-11T02:26:30.160
<p>Under normal operation, the value of a joystick's ADC range on my board is from 0 to 1023 (10-bits). However, my graph for either axis is not continuous. Rather, there is more than one min and maximum for both axis. I am running this thread on a MSP432P401R however the code isn't any different than an Arduino.</p> <pre><code>int jumpFlag; int backwardsFlag; int forwardsFlag; int selPin = P5_1; //Select digital pin location int xOutPin = A14; int yOutPin = A13; void setupPlayerActions() { pinMode(selPin, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(selPin),jumpISR,RISING); //pinMode(xOutPin, ); //Analog X pin setup //pinMode(xOutPin, ); //Analog Y pin setup } void jumpISR() { Serial.println(&quot;Jump Detected!&quot;); jumpFlag = 1; } void loopPlayerActions() { int x_adc_val, y_adc_val; int leftThreshold=50,rightThreshold=900; float x_volt, y_volt; x_adc_val = analogRead(xOutPin); y_adc_val = analogRead(yOutPin); x_volt = ( ( x_adc_val )); /*Convert digital value to voltage */ y_volt = ( ( y_adc_val)); /*Convert digital value to voltage */ if (x_volt &lt; leftThreshold){ Serial.println(&quot;Move Backwards&quot;); } else if (x_volt &lt; rightThreshold){ Serial.println(&quot;Move Forwards&quot;); } Serial.println(&quot;X_Voltage = &quot;); Serial.print(x_volt); Serial.print(&quot;\t&quot;); //Serial.print(&quot;Y_Voltage = &quot;); //Serial.println(y_volt); delay(100); //delay(250); } </code></pre> <p>The graph goes to zero for all positive x and y integers however it briefly reaches a maximum past a small value on the -x and -y axis then sinks to about ~420. What could be causing this?</p>
<p>A 10 bit ADC may not have 10 bits of resolution for a given sample. It might only have 5 or 6 bits due to random noise and other factors. Consult the chip manufactures specifications / recommendations if you need a specific number.</p> <p>What can be done?</p> <ul> <li>If response time is not an issue, consider averaging the ADC reading. A common coding practice is to use an <a href="https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average" rel="nofollow noreferrer">exponential moving average</a>.</li> <li>Consider a better ADC. Many times a dedicated ADC chip (not integrated into a processor) will have better specifications.</li> </ul> <p>For more in depth reading <a href="https://www.nxp.com/docs/en/application-note/AN5250.pdf" rel="nofollow noreferrer">this NXP (aka: Motorola, Freescale) application note</a> discusses &quot;How to Increase the Analog-to-Digital Converter Accuracy in an Application&quot;.</p>
89611
|float|functions|
parseFloat() function
2022-05-11T18:17:23.667
<p>I have noticed that the parseFloat() function returns decimal numbers, but only up to 2 decimal places. Would it be possible for it to return the numbers with more decimal places? In case we need more precision</p>
<blockquote> <p>the <code>parseFloat()</code> function returns decimal numbers</p> </blockquote> <p>No, it doesn't. It returns a <strong>binary</strong> (not decimal) floating point number.</p> <blockquote> <p>only up to 2 decimal places</p> </blockquote> <p>The number returned by <code>parseFloat()</code> has 24 significant digits. Binary digits, that is, also called “bits”. This is roughly equivalent to 7 decimal digits.</p> <p>That being said, beware of <code>Serial.print()</code>. This function converts binary floating point numbers to decimal, and defaults to showing only two digits after the radix point. You can ask for more:</p> <pre class="lang-cpp prettyprint-override"><code>Serial.println(x, 6); // display x with 6 digits after the radix point. </code></pre> <p>If you want to gain some basic understanding of how floating point numbers work, I recommend reading <a href="https://floating-point-gui.de/" rel="nofollow noreferrer">The Floating-Point Guide - What Every Programmer Should Know About Floating-Point Arithmetic</a>.</p>
89633
|arduino-mega|battery|current|solar|
Arduino battery capacity selection based on the current measurements
2022-05-15T13:00:25.100
<p>I'm sorry for this stupid question... I'm not an electronic/electric expert.. In order to select the battery capacity as well as the solar panel I'm measuring the Arduino current consumption. So, I connected my multimeter (in line) (I rotated the selector on 200mA) and I'm able to see the values that are:</p> <ul> <li>around 85mA for  few seconds (around 8seconds) when the system works;</li> <li>around 0.38 mA during the remaining 52 seconds when the system is in sleep mode. I'll enable my system around 8s for each 15minutes (basically 4 times for hour)</li> </ul> <p>In order to have a general idea, I would like to use a site like this <a href="https://www.digikey.it/en/resources/conversion-calculators/conversion-calculator-battery-life" rel="nofollow noreferrer">https://www.digikey.it/en/resources/conversion-calculators/conversion-calculator-battery-life</a></p> <p>Now, It's not clear for me how can I use the retrieved values: Do I calculate the current consuming in 1h?</p> <p>The values that I obtained are related to the current consumed for a second? </p> <p>What I have to punt into the field &quot;Device Consumption&quot; on the linked web-site?</p>
<p>You have two current values and the approximate time those currents run for. From that you can calculate the <em>average</em> current.</p> <p>If you have 8 seconds &quot;on&quot; and (15*60-8) 892 seconds &quot;off&quot; that gives you:</p> <pre><code>(85 * 8) + (0.38 * 892) ------------------------ 900 </code></pre> <p>Which comes out as 1.13mA on average at any point in time (that's a simple ratio calculation - the times don't matter, only the ratio between them).</p> <p>Over the course of 1 hour you will consume around 1.13mA on average, which is 1.13mAh.</p> <p>To run for 24 hours you will need 1.13<em>24 = 27.2mAh. To run for a week it's 27.2</em>7 = 190mAh.</p> <p>The calculations, as you can see, once you have the average current are pretty simple.</p> <p>Of course you need to &quot;derate&quot; the results since batteries <em>never</em> hold the stated amount - that is both a &quot;theoretical maximum&quot; under ideal conditions, which degrades over time (as you will know when your phone battery starts dying too soon), plus you <em>never</em> run a battery completely flat. Personally I like to double the capacity to err on the safe side.</p> <p>You also know that you need to charge the batteries with at least an average of 1.13mA from your solar cells. That means working out what ratio of the time will be available for actual charging (daylight with good sun brightness) and calculating how much current you will need to generate during that time to allow the system to run in the dark.</p>
89646
|arduino-uno|c|
Can't get input from 4x4 keyboard
2022-05-16T19:09:59.310
<p>I'd like to make some basic calculator. Currently, I'm struggling with inputs. I wanted to get from user some numerical input, then, I'd like to have an information, which type of calculation he is about to do. I'm not sure why, but I can't get any numerical input from user, because the program &quot;jumps&quot; ahead to the operation type. Here's some code:</p> <pre><code>void loop(){ int a = getNumber(); if(a != NO_KEY){ do{ operationType = getOperationType(); }while(!operationType); } </code></pre> <p>}</p> <p><strong>getNumber</strong></p> <pre><code> int getNumber(){ char userInput = customKeypad.getKey(); int value; if (userInput == '0' || userInput == '1' || userInput == '2' || userInput == '3' || userInput == '4' || userInput == '5' || userInput == '6' || userInput == '7' || userInput == '8' || userInput == '9'){ value = userInput - '0'; Serial.println(&quot;value&quot;); Serial.println(value); } return value; } </code></pre> <p><strong>getOperationType</strong></p> <pre><code>char getOperationType(){ char userInput = customKeypad.getKey(); switch (userInput){ case '+': // add(a , b); Serial.println(&quot;add&quot;); break; case '-': // subtract(a , b); Serial.println(&quot;subtract&quot;); break; case '*': // multiply(a , b); Serial.println(&quot;multiply&quot;); break; case '/': // divide(a , b); Serial.println(&quot;Divide&quot;); break; case 'C': // TODO break; } return userInput; } </code></pre> <p>Can I have any hint, why I can't just get simple inputs from the keyboard?</p>
<p>You need to watch out for what you return and if your variables are initialized. So, what happens here:</p> <p>In <code>loop()</code> you call <code>getNumber()</code>. There you declare two variables:</p> <ul> <li><code>userInput</code>, which you initialize to the return value of <code>customKeypad.getKey()</code>. So this variable will have the value <code>NO_KEY</code> if no key is pressed.</li> <li><code>value</code>, which you don't initialize. Thus its value is whatever was there in the variables memory space before it was allocated. This can be anything, but it is not random in most cases. It depends on what your program does prior to this, but you don't have any control over it.</li> </ul> <p>Then you check for <code>userInput</code> being an ASCI digit. As you didn't press a key this obviously is false, so the variable <code>value</code> gets never written. And then you return that variable.</p> <p>In <code>loop()</code> you check if the return value of <code>getNumber()</code> is unequal to <code>NO_KEY</code>. And since you didn't initialize <code>value</code>, it probably is. Thus the program goes directly to the operation type part.</p> <hr /> <p><strong>What to do now?</strong></p> <p>First: Always initialize every variable that you declare in a function. Global variables get initialized implicitly, but not local variables. To be sure that I don't make an error, I just always initialize ALL my variables when declaring them.</p> <p>Second: Currently <code>value</code> will not be <code>NO_KEY</code> since you don't assign that value to the variable. But doing so wouldn't fit with your program logic. <code>value</code> is the real numeric value, not the ASCI representation of it. And <code>NO_KEY</code> is defined in the <code>Keypad</code> library as <code>\0</code> (the null character, with numeric value zero). So <code>NO_KEY</code> is actually equal to <code>0</code>. And zero is also a valid input to your calculator.</p> <p>Instead I would suggest returning <code>-1</code> if no key was pressed and then in <code>loop()</code> checking for that. So something like this:</p> <pre><code>int getNumber(){ char userInput = customKeypad.getKey(); int value; if (userInput == '0' || userInput == '1' || userInput == '2' || userInput == '3' || userInput == '4' || userInput == '5' || userInput == '6' || userInput == '7' || userInput == '8' || userInput == '9'){ value = userInput - '0'; Serial.println(&quot;value&quot;); Serial.println(value); } else { return -1; } return value; } void loop(){ int a = getNumber(); if(a != -1){ do{ operationType = getOperationType(); }while(!operationType); } } </code></pre> <hr /> <p>That said, I have some suggestions for you for going further:</p> <ul> <li><p>For checking if the returned key is an ASCII digit there is actually a simple function for that: <code>isDigit()</code>. So instead of your chained equal conditions you can just use</p> <pre><code> if(isDigit(userInput)) </code></pre> </li> <li><p>If you go on in this style you will find yourself wrapping multiple loops in one another as you need to loop for waiting on a keypress. That can get rather messy and it gets difficult to add additional functionality. Instead you could implement a Finite State Machine (FSM). Here the code in <code>loop()</code> consists mainly out of a switch case structure, where every case is one state of your program. For example you could have the states NUMBER1_INPUT, OPERATION_INPUT, NUMBER2_INPUT, DISPLAY_RESULT. The switch structure uses a single int variable as a state marker. For example when you set that state variable to NUMBER1_INPUT it will stay there and loop. When the user as done the number input you can change the state variable to OPERATION_INPUT and let it continue there. It is an important concept and it will change your way of Arduino coding for the better.</p> <p>There are many resource for learning how to program a FSM. I've once written <a href="https://arduino.stackexchange.com/questions/63488/wanted-to-control-2-servos-with-serial-read/63491#63491">a longer answer about this</a>, but you can search for something like &quot;Finite State Machine&quot; on this site or the web to find out more.</p> </li> </ul>
89647
|serial|arduino-nano|power|usb|port-mapping|
USB-C to USB-C cable Arduino is not responding even not powered by this cable
2022-05-16T19:27:19.393
<p>Hi I want to connect arduino NANO to my laptop with Type-C (USB-C) ports (on below image left side [4] and other side <a href="https://i.stack.imgur.com/J0Okp.jpg" rel="nofollow noreferrer">3</a>). Now I bought a USB-C to USB-C cable, because it appeared to be the right tool, but the Arduino is not even powered by this cable. if I use regular USB 3.2 Gen 2 Port (on below image [5]) everythings for fine. but this usb-c ports not recognize the Arduino NANO even NANO's power LED is not switching ON.</p> <p>On the other hand If I plug in my phone to this usb-c cable it works both ports. It means that cable is working good. I have changed 2 times cable stil not responding.</p> <p>On the <a href="https://www.manua.ls/msi/gs66-stealth/manual?p=18" rel="nofollow noreferrer">docs</a>, it look usb-c and regular usb 3.2 ports works same. But why usb-c ports not working with Arduino. also my laptop is MSI GS66</p> <p><a href="https://i.stack.imgur.com/1fQPQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1fQPQ.jpg" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/J0Okp.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J0Okp.jpg" alt="enter image description here" /></a></p> <p>I'd appreciate if anyone has a solution or an idea to fix it. Thanks!</p>
<p>That Nano is not USB-C compliant. Yes, it has the connector, but it doesn't do all the required handshaking to put the USB-C port on the laptop into host (and provide power) mode. This is needed because those ports are also power inputs and have to be told to output power - otherwise plug in power to them and bang horrible things happen.</p> <p>You have to use the larger USB 3.2 ports which are always power providers and never power consumers.</p>
89666
|programming|esp32|library|json|
Arduino create Json Array with double values and 2 decimal point
2022-05-18T12:39:53.057
<p>How i can create a Json Array with double values and 2 decimal point using the ArduinoJson Library?</p> <p><a href="https://arduinojson.org/v6/how-to/configure-the-serialization-of-floats/" rel="nofollow noreferrer">https://arduinojson.org/v6/how-to/configure-the-serialization-of-floats/</a></p> <p>In the folowing small example it is possible to write to the Json file a double value with 2 decimal point.</p> <pre><code>#include &lt;ArduinoJson.h&gt; double round2(double value) { return (int)(value * 100 + 0.5) / 100.0; } double round3(double value) { return (int)(value * 1000 + 0.5) / 1000.0; } double var1 = 1.23456789; double var2 = 5.05599991; void setup() { Serial.begin(115200); StaticJsonDocument&lt;200&gt; doc; doc[&quot;hello&quot;] = &quot;world&quot;; doc[&quot;var1&quot;] = round2(var1); doc[&quot;var2&quot;] = round3(var2); serializeJsonPretty(doc, Serial); } </code></pre> <p>In my sketch right now i am able to create the Json Array with the values read from a Analog input. Only the created Json Array have 9 decimal points. I do not know how to implement in my sketch, folowing the aboth example that the values inside the Json array have only two decimal points.</p> <p>Follow my sketch.</p> <pre><code>#include &lt;ArduinoJson.h&gt; #define ADC_Range_Pin 35 // Pin Range Sensor unsigned long scale_previousMillis = 0; const long scale_interval = 100; // Interval const byte NUM_SAMPLES = 20; double buffer_range [NUM_SAMPLES]; // Range Sensor Instanzen----------------------------- double Current_range = 0; //4-20 mA double rawADCValue_range = 0; double ADCVoltage_range = 0; //0-3,3 V double range = 0; //0-50mm unsigned long range_t; double mapfloat(double x, double in_min, double in_max, double out_min, double out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } double round_range(double value) { return (int)(value * 100 + 0.5) / 100.0; } void Read_Scale() { StaticJsonDocument&lt;1000&gt; doc; static int scale_counter = 0; if (millis() - scale_previousMillis &gt;= scale_interval) { scale_previousMillis = millis(); rawADCValue_range = 0; for (int i = 0; i &lt; 100; ) { if (millis() - range_t &gt;= 1) { rawADCValue_range += analogRead(ADC_Range_Pin); i++; range_t = millis(); } } ADCVoltage_range = (double)(rawADCValue_range / 100.0) * (3.3 / 4095.0); Current_range = mapfloat(ADCVoltage_range, 0.8, 3.3, 4, 20); range = mapfloat(Current_range, 4, 20, 0, 50); buffer_range[scale_counter] = range ; scale_counter ++; JsonArray rangeValues = doc.createNestedArray(&quot;Range&quot;); if (scale_counter &gt;= NUM_SAMPLES) { for (int i = 0; i &lt; NUM_SAMPLES; i++) { rangeValues.add (buffer_range[i]); } serializeJson(doc, Serial); Serial.println(); scale_counter = 0; Serial.println(); } } } void setup() { Serial.begin(115200); } void loop() { Read_Scale(); } </code></pre>
<p>You defined the rounding function <code>round_range()</code>, but never used it. You want to round the numbers that you are putting into the array within the JSON document:</p> <pre class="lang-cpp prettyprint-override"><code>rangeValues.add(round_range(buffer_range[i])); </code></pre>
89688
|esp32|web-server|
Generalize webserver routing
2022-05-21T18:32:02.080
<p>I'm following the examples for ESP32:</p> <pre><code> AsyncWebServer _server(80); _server.on(&quot;/&quot;, HTTP_GET, [](AsyncWebServerRequest *request) { request-&gt;send(SPIFFS, &quot;/index.html&quot;, String(), false); }); _server.on(&quot;/css/index.css&quot;, HTTP_GET, [](AsyncWebServerRequest *request){ request-&gt;send(SPIFFS, &quot;/css/index.css&quot;, &quot;text/css&quot;); }); _server.onNotFound([](AsyncWebServerRequest *request){ request-&gt;send(404); }); _server.begin(); </code></pre> <p>With this approach I have to know in advance each file I store in the <code>SPIFFS</code> and add a handler for each one.</p> <p>Is there a more elegant way to automatically serve any file that exists in the flash?</p>
<p>You can tell the webserver to serve the static content from a specific folder:</p> <pre><code>server.serveStatic(&quot;/&quot;, SPIFFS, &quot;/&quot;).setDefaultFile(&quot;index.html&quot;); </code></pre> <p>In this case it serves on the root URL the content from the SPIFFS root. So if I place a file called <code>image.jpg</code> in the SPIFFS root it will be served at <code>/image.jpg</code>. For more information you can look at <a href="https://github.com/me-no-dev/ESPAsyncWebServer#serving-static-files" rel="nofollow noreferrer">the corresponding section of the libraries Readme file</a>.</p>
89705
|esp8266|array|
How to append to array of Strings in arduino?
2022-05-23T12:17:31.720
<p>Here is my code:</p> <pre class="lang-cpp prettyprint-override"><code>char *StrAB[] = {&quot;29 EC C7 C1&quot;, &quot;69 5B C9 C2&quot;, &quot;22 3B 83 34&quot;, &quot;12 BF BF 34&quot;, &quot;C6 78 8E 2C&quot; }; void setup() { Serial.begin(9600); } void loop() { for (int i = 0; i &lt; sizeof(*StrAB)+1; i++) { Serial.println(StrAB[i]); delay(1000); } Serial.println(sizeof(*StrAB)+1); StrAB[sizeof(*StrAB)+1]= &quot;00 00 00 00&quot;; } </code></pre> <p>I'm trying to append to the end of array of strings but it doesn't work? How can I delete a string from the array?</p>
<p>As stated by Sim Son in a comment, an array is a fixed-size data structure in C++. You thus have to choose beforehand a suitable size, and then keep track of how much of the array is actually used. For example:</p> <pre class="lang-cpp prettyprint-override"><code>const int AB_max = 10; // array capacity const char *AB_str[AB_max] = {&quot;29 EC C7 C1&quot;, &quot;69 5B C9 C2&quot;, &quot;22 3B 83 34&quot;, &quot;12 BF BF 34&quot;, &quot;C6 78 8E 2C&quot;}; int AB_count = 5; // used slots </code></pre> <p>To add a string to this array, you write it to the next available slot. But you have first to make sure there is still room available:</p> <pre class="lang-cpp prettyprint-override"><code>void AB_add(const char *s) { if (AB_count &lt; AB_max) AB_str[AB_count++] = s; } </code></pre> <p>If you want to remove an item (other than the last one), you will have to shift all the following items down the array. The <code>memmove()</code> function comes handy for this:</p> <pre class="lang-cpp prettyprint-override"><code>void AB_remove(const char *s) { // Find the index of s. int i; for (i = 0; i &lt; AB_count; i++) if (strcmp(s, AB_str[i]) == 0) break; // Do nothing if not found. if (i == AB_count) return; // Move subsequent items down the array. memmove(&amp;AB_str[i], &amp;AB_str[i+1], (AB_count - (i + 1)) * sizeof *AB_str); AB_count--; } </code></pre> <p>Note that moving these items down can be costly if the array is pretty long. An array may then not be the best data structure for you. I wouldn't worry though if it's just a dozen items or so.</p> <p>Here is now a small test for all of the above:</p> <pre class="lang-cpp prettyprint-override"><code>void AB_print() { Serial.print(&quot;AB: &quot;); Serial.print(AB_count); Serial.println(&quot; items&quot;); for (int i = 0; i &lt; AB_count; i++) { Serial.print(&quot; &quot;); Serial.println(AB_str[i]); } Serial.println(); } void setup() { Serial.begin(9600); AB_print(); AB_add(&quot;00 00 00 00&quot;); AB_print(); AB_remove(&quot;12 BF BF 34&quot;); AB_print(); } void loop() {} </code></pre> <p>Note that this is a very “C” style of doing things. If you want to go to more idiomatic C++, you can start by putting everything that is named with the prefix <code>AB_</code> inside a class.</p> <p>If you really want an array where you can vary the length, you may allocate it with <code>malloc()</code> and resize it with <code>realloc()</code>. These functions, however, are not very friendly to memory-constrained devices. They are thus often avoided in the embedded world. They may also not play well with code that uses <code>new</code> and <code>delete</code>, including library code that you may not be aware of.</p>
89706
|sensors|arduino-due|digital|keyboard|
Adjusting Threshold for Digital Pins
2022-05-23T12:39:46.837
<p>I am working on a project using Force Sensors to build a keyboard for MD patients. I have connected the sensors (each with 4 input pins) to <strong>digital pins</strong> to <em>Arduino Due</em>. I want to adjust the threshold of the digital pins in order to cancel out the initial weight of a user's hand when using the keyboard. I have read that digital pins have a built-in threshold (&quot;low&quot;&lt;0.3 Vcc and &quot;high&quot;&gt;0.6Vcc). I can't connect my sensors to Analog pins (due to needing 20 input pins), and was wondering if adjusting the threshold is possible? I have researched and found one project that used Analog pins and adjusted the threshold, which I am trying to emulate: <a href="https://www.instructables.com/Arduino-Programmable-Button-Panel-As-Keyboard/" rel="nofollow noreferrer">https://www.instructables.com/Arduino-Programmable-Button-Panel-As-Keyboard/</a> P.S: I am a beginner at Arduino and would appreciate the help</p>
<p>No, you cannot change these threshold. They are set by the digital input hardware (technically a Schmitt trigger) inside the microcontroller. They are not meant to be adjustable, since they are digital input, not analog inputs.</p> <p>So you either need to build your own adjustable logic (involving opamps and variable resistors), feeding the output of that to the Arduino, or you need to use analog inputs.</p> <p>I would suggest using the second method. You can extend the number of analog inputs basically by 2 means:</p> <ul> <li><p>You can buy analog multiplexers. These are chips that can connect one analog input of the Arduino on one side to X pins on the other side. Most of them are controlled via digital pins. Then you cycle through each setting of the multiplexer to connect one sensor at a time and do a measurement on each of them. Each analog pin can be connected to one analog multiplexer</p> </li> <li><p>You can buy an external ADC board. These are often connected via interfaces like I2C or SPI (for example <a href="https://www.adafruit.com/product/1085" rel="nofollow noreferrer">this one from Adafruit</a> with 4 channels each). You can use multiple of them.</p> </li> </ul>
89708
|esp32|adc|potentiometer|
ESP32 Potentiometer issue: Resolution mismatch of the potentiometer with unlimited resolution and reading the values with Wire.h
2022-05-23T14:04:51.033
<p>I have the problem, that the potentiometer goes from the range of 0 Volts to 3,3 volts. But within this range the measured value goes <strong>from about 0 to 65535 multiple times</strong> (over 10 cycles).</p> <p>When I change the code from my ADC library to 32 bit I get 32 bit values (0 - 4294967296) but the same error with the beginning at 0 multiple times within the potentiometer range occurs.</p> <p><strong>Hardware:</strong></p> <p><strong>Board:</strong> ESP32 <strong>ADC:</strong> MAX11613 (12 bit adc) <a href="https://www.mouser.de/datasheet/2/256/MAX11612-MAX11617-1508955.pdf" rel="nofollow noreferrer">https://www.mouser.de/datasheet/2/256/MAX11612-MAX11617-1508955.pdf</a> <strong>Potentiometer:</strong> 3046L - 3 - 203 <a href="https://www.mouser.de/datasheet/2/54/3046-776396.pdf" rel="nofollow noreferrer">https://www.mouser.de/datasheet/2/54/3046-776396.pdf</a></p> <p>Part of the code that reads the adc values:</p> <pre><code>uint8_t MAX11613::MAX11613_ADC_Read(structMAX11613* chip, uint8_t channel, uint16_t* val){ uint8_t configurationByte = ( (channel&lt;&lt;1) &amp; 0x0e) | 0x61; MAX11613_Configuration(chip, configurationByte); Wire.beginTransmission(chip-&gt;devAddress); Wire.requestFrom(chip-&gt;devAddress, (byte) 2); // request 2 bytes from slave device wireIface while (Wire.available()) { // slave may send less than requested //char c = Wire.read(); // receive a byte as character uint16_t value = 0; value = Wire.read(); value |= Wire.read() &lt;&lt; 8; //This also works: /*uint32_t buf1; size_t actually_read = Wire.readBytes((uint8_t*)&amp;buf1, 2); *val = actually_read; //Serial.println(value);*/ *val = value; } if (Wire.endTransmission() != 0){ return 1; } return 0; } </code></pre>
<p>The MAX1161x are 12-bit ADCs, so the problem is not related to an uint16 overflow as you seem to assume. The ADC transmits most significant bits (MSB) first as can be seen <a href="https://www.mouser.de/datasheet/2/256/MAX11612-MAX11617-1508955.pdf" rel="nofollow noreferrer">in figure 10 on page 17</a>. To account for that you need to change</p> <pre><code>value = Wire.read(); value |= Wire.read() &lt;&lt; 8; </code></pre> <p>to</p> <pre><code>value = Wire.read() &lt;&lt; 8; value |= Wire.read(); </code></pre>
89712
|arduino-uno|led|photoresistor|
Apparently the photoresistors don't pass the input at the leds
2022-05-23T16:20:38.143
<p>I am making a school project where i need to create a parking loot in tinkercad. Me and my mate tried to use a bunch of photoresistor that worked as a sensor. No light = car = red led; light = no car = green led. We can't figure out why the leds dont turn on. We are still on a low level of abilities on this type of work and in class we didn't see a lot of components, so the photoresistor were one of the best choice.</p> <p>Here is the screenshot of the whole project, it's in italian so if you guys needs a transduction of the variable just tell me. Don't mind the button, we were trying something.</p> <p><a href="https://i.stack.imgur.com/BFUHo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BFUHo.png" alt="enter image description here" /></a></p> <p>Here is the code: In this line &quot;if(analogRead(fotoresistori[i]) &lt; 300)&quot; we put 300 because with 0 etc. it did not work</p> <pre><code>int fotoresistori[] = {A0, A1, A2, A3, A4}; int verdi[] = {11, 10, 9, 8, 7}; int rossi[] = {6, 5 , 4, 3, 2}; void setup() { pinMode(13, INPUT); pinMode(12, INPUT); pinMode(11, OUTPUT); pinMode(10, OUTPUT); pinMode(9, OUTPUT); pinMode(8, OUTPUT); pinMode(7, OUTPUT); pinMode(6, OUTPUT); pinMode(5, OUTPUT); pinMode(4, OUTPUT); pinMode(3, OUTPUT); pinMode(2, OUTPUT); Serial.begin(9600); } void loop() { Serial.println(postiDisponibili); if(digitalRead(13) == HIGH){ postiDisponibili++; } else if(digitalRead(12) ){ postiDisponibili--; } for(int i = 0; i&lt;5; i++){ if(analogRead(fotoresistori[i]) &lt; 300){ digitalWrite(rossi[i], HIGH); digitalWrite(verdi[i], LOW); }else{ digitalWrite(rossi[i], LOW); digitalWrite(verdi[i], HIGH); } } delay(500); } </code></pre> <p>The value of A0 is always at 0.</p>
<p>You're not applying any voltage to the photoresistors and the other end is connected to earth so it will always be zero. You need to connect the analog end to +5v via a suitable current limiting resistor (suggest 10K for a typical photoresistor) then measure the voltage.</p>
89720
|arduino-uno|arduino-ide|
How to do multiple serial.read()
2022-05-24T02:10:29.460
<p>first of all im new here and im really sorry if there's some mistakes when im making this question. So im trying to make a program to calculate using serial read, and im going to input a lot of values.</p> <p>These are the codes that im trying to upload, but it wont shows the input.</p> <pre><code>int PpmNeed; int Ppmpertank; int nyala; int tangki; int sensor; int mlkeluar; int perlakuan; void setup() { Serial.begin(115200); Serial.setTimeout(10); } void loop() { Serial.println(&quot;Besar Tangki&quot;); while(Serial.available() == 0){} tangki = Serial.parseInt(); Serial.println(&quot;Kadar Dari Sensor&quot;); while(Serial.available() == 0){} sensor = Serial.parseInt(); Serial.println(&quot;Data Perlakuan&quot;); while(Serial.available() == 0){} perlakuan = Serial.parseInt(); Serial.print(&quot;Besar Tangki : &quot;); Serial.println(tangki); Serial.print(&quot;Kadar Dari Sensor : &quot;); Serial.println(sensor); Serial.print(&quot;Data Perlakuan : &quot;); Serial.println(perlakuan); } </code></pre>
<p>While your way to read the input from user is sub-optimal, to make it work you have to read the new line characters Serial Monitor sends (if line ending are selected in the drop down box).</p> <p>The new line characters are available on Serial after the digits, so they make</p> <pre><code>while(Serial.available() == 0){} </code></pre> <p>to end immediately.</p> <p>You can patch it up by reading the trailing line ending characters.</p> <pre><code>int PpmNeed; int Ppmpertank; int nyala; int tangki; int sensor; int mlkeluar; int perlakuan; void setup() { Serial.begin(115200); Serial.setTimeout(10); } void loop() { Serial.println(&quot;Besar Tangki&quot;); while (Serial.available()) { Serial.read(); } while(Serial.available() == 0){} tangki = Serial.parseInt(); Serial.println(&quot;Kadar Dari Sensor&quot;); while (Serial.available()) { Serial.read(); } while(Serial.available() == 0){} sensor = Serial.parseInt(); Serial.println(&quot;Data Perlakuan&quot;); while (Serial.available()) { Serial.read(); } while(Serial.available() == 0){} perlakuan = Serial.parseInt(); Serial.print(&quot;Besar Tangki : &quot;); Serial.println(tangki); Serial.print(&quot;Kadar Dari Sensor : &quot;); Serial.println(sensor); Serial.print(&quot;Data Perlakuan : &quot;); Serial.println(perlakuan); } </code></pre>
89725
|arduino-uno|lcd|adafruit|
What are these 18 extra ports on the adafruit-gfx 2.8"
2022-05-24T12:36:48.963
<p>I recently got the Adafruit gfx 2.8&quot; display, which works fine.</p> <p>It's quite obvious that it requires almost all of the pins on the UNO. <em>However, I don't understand what are the 18 avaliable &quot;soldier ports&quot; are at the bottom of the Adafruit shield.</em></p> <p>Can these ports be used with sensors, ie: push button, so you wouldn't need to plug anything else into the UNO board? What do these holes do? I'm unable to find out, as it doesn't seem to be a common shield, most Adafruit shields don't seem to have those ports.</p> <p>If these ports do nothing, should I saw them off - save space?</p> <p><a href="https://i.stack.imgur.com/ef0YR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ef0YR.jpg" alt="enter image description here" /></a></p>
<p>Those are an alternative way of connecting to the screen. Basically they mirror the connections to the &quot;shield&quot; pins.</p> <p>To save costs the manufacturer will have made a PCB that can be used in multiple different ways just by soldering different connectors. In this case either as an Arduino shield or as a board on the end of a ribbon cable. You have the version with the Arduino shield pins soldered in.</p> <p>They are of no use to you unless you should want to put the screen on the end of a ribbon cable. Can you remove them? Possibly, possibly not. It depends on how the PCB traces are routed. Cutting the board may cut important PCB traces that connect the screen to the Arduino shield pins.</p> <p>Only close inspection of the board and understanding the routing of the traces will be able to tell you yes or no. If in doubt, though, no you don't want to be randomly cutting off chunks of the circuit.</p>
89730
|arduino-uno|sensors|i2c|serial-data|
My Atlas Scientific sensors measurement give zero values at first reading
2022-05-25T08:30:52.927
<p>I am still continuing my <a href="https://arduino.stackexchange.com/questions/89451/i2c-sensors-not-working-when-i-connect-to-lcd-20x04">hydroponic nutrient monitoring project</a>. In short, I made a hydroponic nutrient monitoring system with I2C connection, and decided to do serial communication with Raspberry Pi 3B+ to save sensor reading data in CSV file. I am curious about why after uploading the sketch, the sensors always gives zero values at first reading on Serial Monitor.</p> <p>This is the screenshot of my Serial Monitor.</p> <p><a href="https://i.stack.imgur.com/aEVSm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aEVSm.jpg" alt="enter image description here" /></a></p> <p>From left to right: timestamp, EC, pH, Temperature.</p> <p>Everytime I reset the Arduino, the Serial Monitor first will show no values. On the second line, it shows only EC value. The third line only EC and pH value, then the fourth line and so on will show all values.</p> <p><strong>How to make the Arduino show all sensor values from the start in the Serial Monitor?</strong></p> <p>Here is my code that I modified from Atlas Scientific page for my project:</p> <pre><code>#include &lt;Ezo_i2c.h&gt; #include &lt;Wire.h&gt; Ezo_board ec = Ezo_board(100, &quot;EC&quot;); Ezo_board ph = Ezo_board(99, &quot;PH&quot;); Ezo_board temp = Ezo_board(102, &quot;RTD&quot;); bool reading_request_phase = true; uint32_t next_poll_time = 0; const unsigned int response_delay = 1000; void setup() { Serial.begin(9600); Wire.begin(); delay(1000); } void loop() { if (reading_request_phase) { ec.send_read_cmd(); ph.send_read_cmd(); temp.send_read_cmd(); next_poll_time = millis() + response_delay; reading_request_phase = false; } else { if (millis() &gt;= next_poll_time) { receive_reading(ec); receive_reading(ph); receive_reading(temp); reading_request_phase = true; } } } void receive_reading(Ezo_board &amp;Sensor) { Sensor.receive_read_cmd(); Serial.println(); Serial.print(ec.get_last_received_reading()/1000); Serial.print(&quot;,&quot;); Serial.print(ph.get_last_received_reading()); Serial.print(&quot;,&quot;); Serial.print(temp.get_last_received_reading()); Serial.print(&quot;&quot;); delay(1000); } </code></pre>
<p>Each time you call <code>receive_reading()</code> you pass it <em>one</em> sensor to read the value from. But each time you call <code>receive_reading()</code> you print out <em>all three</em> sensors.</p> <p>So you:</p> <ol> <li>Read EC and print EC PC TEMP</li> <li>Read PC and print EC PC TEMP</li> <li>Read TEMP and print EC PC TEMP</li> </ol> <p>In step one you only have EC, you haven't read PC or TEMP yet. In step two you have the old reading of EC and a new PC reading but still no TEMP reading. By step three you finally have a TEMP reading but still the old EC and PC readings from earlier.</p> <p>You should instead put the receiving command (<code>Sensor.receive_read_cmd()</code>) once for each sensor as a separate thing to displaying the received values. More like:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;Ezo_i2c.h&gt; #include &lt;Wire.h&gt; Ezo_board ec = Ezo_board(100, &quot;EC&quot;); Ezo_board ph = Ezo_board(99, &quot;PH&quot;); Ezo_board temp = Ezo_board(102, &quot;RTD&quot;); bool reading_request_phase = true; uint32_t next_poll_time = 0; const unsigned int response_delay = 1000; void setup() { Serial.begin(9600); Wire.begin(); delay(1000); } void loop() { if (reading_request_phase) { ec.send_read_cmd(); ph.send_read_cmd(); temp.send_read_cmd(); next_poll_time = millis() + response_delay; reading_request_phase = false; } else { if (millis() &gt;= next_poll_time) { ec.receive_read_cmd(); ph.receive_read_cmd(); temp.receive_read_cmd(); display_reading(); reading_request_phase = true; } } } void display_reading() { Serial.print(ec.get_last_received_reading()/1000); Serial.print(&quot;,&quot;); Serial.print(ph.get_last_received_reading()); Serial.print(&quot;,&quot;); Serial.println(temp.get_last_received_reading()); } </code></pre> <p>Also remove the <code>delay()</code> after each printed line, it's just confusing everything and slowing down your reading.</p>
89735
|compilation-errors|
error: 'MonoOutput' has not been declared (Mozzi library, Arduino Nano)
2022-05-25T17:35:39.197
<p>I know this error is specific to this particular family of sketches, but please bear with me; when I try to compile this against an Arduino Nano/Uno (with Arduino IDE 1.8.15) the compiler complains that 'MonoOutput' has not been declared, like so:</p> <pre class="lang-cpp prettyprint-override"><code>Triple_DCO_1.3:697:14: error: 'MonoOutput' has not been declared return MonoOutput::from8Bit((aSin1.next() * (pgm_read_byte(&amp;(gain_table[0][gain]))) / 512 + aSin2.next() * (pgm_read_byte(&amp;(gain_table[1][gain]))) / 512 + aSin3.next() * (pgm_read_byte(&amp;(gain_table[2][gain]))) / 512 + aSin4.next() * (pgm_read_byte(&amp;(gain_table[3][gain]))) / 512 + aSin5.next() * (pgm_read_byte(&amp;(gain_table[4][gain]))) / 512 + aSin6.next() * (pgm_read_byte(&amp;(gain_table[5][gain]))) / 512 + aSin7.next() * (pgm_read_byte(&amp;(gain_table[6][gain]))) / 512 )*Gain_CV_2/128); ^~~~~~~~~~ </code></pre> <p>I have found that this issue has come up once on ModWiggler, once in YouTube comments, and once in the Mozzi GitHub repository (but in the last case only pertaining to the <em>Nano Every</em> and not a vanilla Nano), so I know it's not unique to my situation; but since most people don't seem to be experiencing this problem, it must be something particular to my setup or am missing something obvious.</p> <p>The code in question (Triple_DCO_1.3.ino) is from <a href="https://github.com/luislutz/Arduino-VDCO" rel="nofollow noreferrer">luislutz</a> GitHub; it is too long to post here, but a different sketch from the same family, pasted below, exhibits the same error for me:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;MozziGuts.h&gt; #include &lt;Oscil.h&gt; // oscillator template #include &lt;tables/saw2048_int8.h&gt; // saw table for oscillator #include &lt;tables/square_no_alias512_int8.h&gt; // saw table for oscillator #include &lt;tables/triangle_hermes_2048_int8.h&gt; // saw table for oscillator #include &lt;tables/sin2048_int8.h&gt; // sine table for oscillator #include &lt;tables/waveshape_chebyshev_3rd_256_int8.h&gt; // sine table for oscillator #include &lt;tables/halfsin256_uint8.h&gt; // sine table for oscillator #include &lt;tables/waveshape_sigmoid_int8.h&gt; // sine table for oscillator #include &lt;tables/phasor256_int8.h&gt; // sine table for oscillator Oscil &lt;SAW2048_NUM_CELLS, AUDIO_RATE&gt; aSaw1(SAW2048_DATA); Oscil &lt;SAW2048_NUM_CELLS, AUDIO_RATE&gt; aSaw2(SAW2048_DATA); Oscil &lt;SAW2048_NUM_CELLS, AUDIO_RATE&gt; aSaw3(SAW2048_DATA); Oscil &lt;SAW2048_NUM_CELLS, AUDIO_RATE&gt; aSaw4(SAW2048_DATA); Oscil &lt;SAW2048_NUM_CELLS, AUDIO_RATE&gt; aSaw5(SAW2048_DATA); Oscil &lt;SQUARE_NO_ALIAS512_NUM_CELLS, AUDIO_RATE&gt; aSqu1(SQUARE_NO_ALIAS512_DATA); Oscil &lt;SQUARE_NO_ALIAS512_NUM_CELLS, AUDIO_RATE&gt; aSqu2(SQUARE_NO_ALIAS512_DATA); Oscil &lt;SQUARE_NO_ALIAS512_NUM_CELLS, AUDIO_RATE&gt; aSqu3(SQUARE_NO_ALIAS512_DATA); Oscil &lt;SQUARE_NO_ALIAS512_NUM_CELLS, AUDIO_RATE&gt; aSqu4(SQUARE_NO_ALIAS512_DATA); Oscil &lt;SQUARE_NO_ALIAS512_NUM_CELLS, AUDIO_RATE&gt; aSqu5(SQUARE_NO_ALIAS512_DATA); Oscil &lt;TRIANGLE_HERMES_2048_NUM_CELLS, AUDIO_RATE&gt; aTri1(TRIANGLE_HERMES_2048_DATA); Oscil &lt;TRIANGLE_HERMES_2048_NUM_CELLS, AUDIO_RATE&gt; aTri2(TRIANGLE_HERMES_2048_DATA); Oscil &lt;TRIANGLE_HERMES_2048_NUM_CELLS, AUDIO_RATE&gt; aTri3(TRIANGLE_HERMES_2048_DATA); Oscil &lt;TRIANGLE_HERMES_2048_NUM_CELLS, AUDIO_RATE&gt; aTri4(TRIANGLE_HERMES_2048_DATA); Oscil &lt;TRIANGLE_HERMES_2048_NUM_CELLS, AUDIO_RATE&gt; aTri5(TRIANGLE_HERMES_2048_DATA); Oscil &lt;SIN2048_NUM_CELLS, AUDIO_RATE&gt; aSin1(SIN2048_DATA); Oscil &lt;SIN2048_NUM_CELLS, AUDIO_RATE&gt; aSin2(SIN2048_DATA); Oscil &lt;SIN2048_NUM_CELLS, AUDIO_RATE&gt; aSin3(SIN2048_DATA); Oscil &lt;SIN2048_NUM_CELLS, AUDIO_RATE&gt; aSin4(SIN2048_DATA); Oscil &lt;SIN2048_NUM_CELLS, AUDIO_RATE&gt; aSin5(SIN2048_DATA); Oscil &lt;CHEBYSHEV_3RD_256_NUM_CELLS, AUDIO_RATE&gt; aChb1(CHEBYSHEV_3RD_256_DATA); Oscil &lt;CHEBYSHEV_3RD_256_NUM_CELLS, AUDIO_RATE&gt; aChb2(CHEBYSHEV_3RD_256_DATA); Oscil &lt;CHEBYSHEV_3RD_256_NUM_CELLS, AUDIO_RATE&gt; aChb3(CHEBYSHEV_3RD_256_DATA); Oscil &lt;CHEBYSHEV_3RD_256_NUM_CELLS, AUDIO_RATE&gt; aChb4(CHEBYSHEV_3RD_256_DATA); Oscil &lt;CHEBYSHEV_3RD_256_NUM_CELLS, AUDIO_RATE&gt; aChb5(CHEBYSHEV_3RD_256_DATA); Oscil &lt;HALFSIN256_NUM_CELLS, AUDIO_RATE&gt; ahSin1(HALFSIN256_DATA); Oscil &lt;HALFSIN256_NUM_CELLS, AUDIO_RATE&gt; ahSin2(HALFSIN256_DATA); Oscil &lt;HALFSIN256_NUM_CELLS, AUDIO_RATE&gt; ahSin3(HALFSIN256_DATA); Oscil &lt;HALFSIN256_NUM_CELLS, AUDIO_RATE&gt; ahSin4(HALFSIN256_DATA); Oscil &lt;HALFSIN256_NUM_CELLS, AUDIO_RATE&gt; ahSin5(HALFSIN256_DATA); Oscil &lt;WAVESHAPE_SIGMOID_NUM_CELLS, AUDIO_RATE&gt; aSig1(WAVESHAPE_SIGMOID_DATA); Oscil &lt;WAVESHAPE_SIGMOID_NUM_CELLS, AUDIO_RATE&gt; aSig2(WAVESHAPE_SIGMOID_DATA); Oscil &lt;WAVESHAPE_SIGMOID_NUM_CELLS, AUDIO_RATE&gt; aSig3(WAVESHAPE_SIGMOID_DATA); Oscil &lt;WAVESHAPE_SIGMOID_NUM_CELLS, AUDIO_RATE&gt; aSig4(WAVESHAPE_SIGMOID_DATA); Oscil &lt;WAVESHAPE_SIGMOID_NUM_CELLS, AUDIO_RATE&gt; aSig5(WAVESHAPE_SIGMOID_DATA); Oscil &lt;PHASOR256_NUM_CELLS, AUDIO_RATE&gt; aPha1(PHASOR256_DATA); Oscil &lt;PHASOR256_NUM_CELLS, AUDIO_RATE&gt; aPha2(PHASOR256_DATA); Oscil &lt;PHASOR256_NUM_CELLS, AUDIO_RATE&gt; aPha3(PHASOR256_DATA); Oscil &lt;PHASOR256_NUM_CELLS, AUDIO_RATE&gt; aPha4(PHASOR256_DATA); Oscil &lt;PHASOR256_NUM_CELLS, AUDIO_RATE&gt; aPha5(PHASOR256_DATA); #define CONTROL_RATE 128 // Hz, powers of 2 are most reliable int freq1 = 110;//base freq int voct = 1000;//external V/OCT LSB int freqv1 = 440;//apply voct int freqv2 = 440; int freqv3 = 440; int freqv4 = 440; int freqv5 = 440; byte note1 = 0;//Root byte note2 = 0;//2nd byte note3 = 0;//3rd byte note4 = 0;//4th byte note5 = 0;//Root byte inv_aply1 = 0; //0 = no inv , 1 = inv , Root byte inv_aply2 = 0; //2nd byte inv_aply3 = 0; //3rd byte inv_aply4 = 0; //4th bool inv_aply5 = 0; //0 = no output root sound , 1 = output root sound int inv = 0; int inv_knob = 0; int chord = 0; byte wave = 0;//0=saw,1=squ,2=tri,3=sin,etc... const static float voctpow[1024] PROGMEM = { 0, 0.004882, 0.009765, 0.014648, 0.019531, 0.024414, 0.029296, 0.034179, 0.039062, 0.043945, 0.048828, 0.05371, 0.058593, 0.063476, 0.068359, 0.073242, 0.078125, 0.083007, 0.08789, 0.092773, 0.097656, 0.102539, 0.107421, 0.112304, 0.117187, 0.12207, 0.126953, 0.131835, 0.136718, 0.141601, 0.146484, 0.151367, 0.15625, 0.161132, 0.166015, 0.170898, 0.175781, 0.180664, 0.185546, 0.190429, 0.195312, 0.200195, 0.205078, 0.20996, 0.214843, 0.219726, 0.224609, 0.229492, 0.234375, 0.239257, 0.24414, 0.249023, 0.253906, 0.258789, 0.263671, 0.268554, 0.273437, 0.27832, 0.283203, 0.288085, 0.292968, 0.297851, 0.302734, 0.307617, 0.3125, 0.317382, 0.322265, 0.327148, 0.332031, 0.336914, 0.341796, 0.346679, 0.351562, 0.356445, 0.361328, 0.36621, 0.371093, 0.375976, 0.380859, 0.385742, 0.390625, 0.395507, 0.40039, 0.405273, 0.410156, 0.415039, 0.419921, 0.424804, 0.429687, 0.43457, 0.439453, 0.444335, 0.449218, 0.454101, 0.458984, 0.463867, 0.46875, 0.473632, 0.478515, 0.483398, 0.488281, 0.493164, 0.498046, 0.502929, 0.507812, 0.512695, 0.517578, 0.52246, 0.527343, 0.532226, 0.537109, 0.541992, 0.546875, 0.551757, 0.55664, 0.561523, 0.566406, 0.571289, 0.576171, 0.581054, 0.585937, 0.59082, 0.595703, 0.600585, 0.605468, 0.610351, 0.615234, 0.620117, 0.625, 0.629882, 0.634765, 0.639648, 0.644531, 0.649414, 0.654296, 0.659179, 0.664062, 0.668945, 0.673828, 0.67871, 0.683593, 0.688476, 0.693359, 0.698242, 0.703125, 0.708007, 0.71289, 0.717773, 0.722656, 0.727539, 0.732421, 0.737304, 0.742187, 0.74707, 0.751953, 0.756835, 0.761718, 0.766601, 0.771484, 0.776367, 0.78125, 0.786132, 0.791015, 0.795898, 0.800781, 0.805664, 0.810546, 0.815429, 0.820312, 0.825195, 0.830078, 0.83496, 0.839843, 0.844726, 0.849609, 0.854492, 0.859375, 0.864257, 0.86914, 0.874023, 0.878906, 0.883789, 0.888671, 0.893554, 0.898437, 0.90332, 0.908203, 0.913085, 0.917968, 0.922851, 0.927734, 0.932617, 0.9375, 0.942382, 0.947265, 0.952148, 0.957031, 0.961914, 0.966796, 0.971679, 0.976562, 0.981445, 0.986328, 0.99121, 0.996093, 1.000976, 1.005859, 1.010742, 1.015625, 1.020507, 1.02539, 1.030273, 1.035156, 1.040039, 1.044921, 1.049804, 1.054687, 1.05957, 1.064453, 1.069335, 1.074218, 1.079101, 1.083984, 1.088867, 1.09375, 1.098632, 1.103515, 1.108398, 1.113281, 1.118164, 1.123046, 1.127929, 1.132812, 1.137695, 1.142578, 1.14746, 1.152343, 1.157226, 1.162109, 1.166992, 1.171875, 1.176757, 1.18164, 1.186523, 1.191406, 1.196289, 1.201171, 1.206054, 1.210937, 1.21582, 1.220703, 1.225585, 1.230468, 1.235351, 1.240234, 1.245117, 1.25, 1.254882, 1.259765, 1.264648, 1.269531, 1.274414, 1.279296, 1.284179, 1.289062, 1.293945, 1.298828, 1.30371, 1.308593, 1.313476, 1.318359, 1.323242, 1.328125, 1.333007, 1.33789, 1.342773, 1.347656, 1.352539, 1.357421, 1.362304, 1.367187, 1.37207, 1.376953, 1.381835, 1.386718, 1.391601, 1.396484, 1.401367, 1.40625, 1.411132, 1.416015, 1.420898, 1.425781, 1.430664, 1.435546, 1.440429, 1.445312, 1.450195, 1.455078, 1.45996, 1.464843, 1.469726, 1.474609, 1.479492, 1.484375, 1.489257, 1.49414, 1.499023, 1.503906, 1.508789, 1.513671, 1.518554, 1.523437, 1.52832, 1.533203, 1.538085, 1.542968, 1.547851, 1.552734, 1.557617, 1.5625, 1.567382, 1.572265, 1.577148, 1.582031, 1.586914, 1.591796, 1.596679, 1.601562, 1.606445, 1.611328, 1.61621, 1.621093, 1.625976, 1.630859, 1.635742, 1.640625, 1.645507, 1.65039, 1.655273, 1.660156, 1.665039, 1.669921, 1.674804, 1.679687, 1.68457, 1.689453, 1.694335, 1.699218, 1.704101, 1.708984, 1.713867, 1.71875, 1.723632, 1.728515, 1.733398, 1.738281, 1.743164, 1.748046, 1.752929, 1.757812, 1.762695, 1.767578, 1.77246, 1.777343, 1.782226, 1.787109, 1.791992, 1.796875, 1.801757, 1.80664, 1.811523, 1.816406, 1.821289, 1.826171, 1.831054, 1.835937, 1.84082, 1.845703, 1.850585, 1.855468, 1.860351, 1.865234, 1.870117, 1.875, 1.879882, 1.884765, 1.889648, 1.894531, 1.899414, 1.904296, 1.909179, 1.914062, 1.918945, 1.923828, 1.92871, 1.933593, 1.938476, 1.943359, 1.948242, 1.953125, 1.958007, 1.96289, 1.967773, 1.972656, 1.977539, 1.982421, 1.987304, 1.992187, 1.99707, 2.001953, 2.006835, 2.011718, 2.016601, 2.021484, 2.026367, 2.03125, 2.036132, 2.041015, 2.045898, 2.050781, 2.055664, 2.060546, 2.065429, 2.070312, 2.075195, 2.080078, 2.08496, 2.089843, 2.094726, 2.099609, 2.104492, 2.109375, 2.114257, 2.11914, 2.124023, 2.128906, 2.133789, 2.138671, 2.143554, 2.148437, 2.15332, 2.158203, 2.163085, 2.167968, 2.172851, 2.177734, 2.182617, 2.1875, 2.192382, 2.197265, 2.202148, 2.207031, 2.211914, 2.216796, 2.221679, 2.226562, 2.231445, 2.236328, 2.24121, 2.246093, 2.250976, 2.255859, 2.260742, 2.265625, 2.270507, 2.27539, 2.280273, 2.285156, 2.290039, 2.294921, 2.299804, 2.304687, 2.30957, 2.314453, 2.319335, 2.324218, 2.329101, 2.333984, 2.338867, 2.34375, 2.348632, 2.353515, 2.358398, 2.363281, 2.368164, 2.373046, 2.377929, 2.382812, 2.387695, 2.392578, 2.39746, 2.402343, 2.407226, 2.412109, 2.416992, 2.421875, 2.426757, 2.43164, 2.436523, 2.441406, 2.446289, 2.451171, 2.456054, 2.460937, 2.46582, 2.470703, 2.475585, 2.480468, 2.485351, 2.490234, 2.495117, 2.5, 2.504882, 2.509765, 2.514648, 2.519531, 2.524414, 2.529296, 2.534179, 2.539062, 2.543945, 2.548828, 2.55371, 2.558593, 2.563476, 2.568359, 2.573242, 2.578125, 2.583007, 2.58789, 2.592773, 2.597656, 2.602539, 2.607421, 2.612304, 2.617187, 2.62207, 2.626953, 2.631835, 2.636718, 2.641601, 2.646484, 2.651367, 2.65625, 2.661132, 2.666015, 2.670898, 2.675781, 2.680664, 2.685546, 2.690429, 2.695312, 2.700195, 2.705078, 2.70996, 2.714843, 2.719726, 2.724609, 2.729492, 2.734375, 2.739257, 2.74414, 2.749023, 2.753906, 2.758789, 2.763671, 2.768554, 2.773437, 2.77832, 2.783203, 2.788085, 2.792968, 2.797851, 2.802734, 2.807617, 2.8125, 2.817382, 2.822265, 2.827148, 2.832031, 2.836914, 2.841796, 2.846679, 2.851562, 2.856445, 2.861328, 2.86621, 2.871093, 2.875976, 2.880859, 2.885742, 2.890625, 2.895507, 2.90039, 2.905273, 2.910156, 2.915039, 2.919921, 2.924804, 2.929687, 2.93457, 2.939453, 2.944335, 2.949218, 2.954101, 2.958984, 2.963867, 2.96875, 2.973632, 2.978515, 2.983398, 2.988281, 2.993164, 2.998046, 3.002929, 3.007812, 3.012695, 3.017578, 3.02246, 3.027343, 3.032226, 3.037109, 3.041992, 3.046875, 3.051757, 3.05664, 3.061523, 3.066406, 3.071289, 3.076171, 3.081054, 3.085937, 3.09082, 3.095703, 3.100585, 3.105468, 3.110351, 3.115234, 3.120117, 3.125, 3.129882, 3.134765, 3.139648, 3.144531, 3.149414, 3.154296, 3.159179, 3.164062, 3.168945, 3.173828, 3.17871, 3.183593, 3.188476, 3.193359, 3.198242, 3.203125, 3.208007, 3.21289, 3.217773, 3.222656, 3.227539, 3.232421, 3.237304, 3.242187, 3.24707, 3.251953, 3.256835, 3.261718, 3.266601, 3.271484, 3.276367, 3.28125, 3.286132, 3.291015, 3.295898, 3.300781, 3.305664, 3.310546, 3.315429, 3.320312, 3.325195, 3.330078, 3.33496, 3.339843, 3.344726, 3.349609, 3.354492, 3.359375, 3.364257, 3.36914, 3.374023, 3.378906, 3.383789, 3.388671, 3.393554, 3.398437, 3.40332, 3.408203, 3.413085, 3.417968, 3.422851, 3.427734, 3.432617, 3.4375, 3.442382, 3.447265, 3.452148, 3.457031, 3.461914, 3.466796, 3.471679, 3.476562, 3.481445, 3.486328, 3.49121, 3.496093, 3.500976, 3.505859, 3.510742, 3.515625, 3.520507, 3.52539, 3.530273, 3.535156, 3.540039, 3.544921, 3.549804, 3.554687, 3.55957, 3.564453, 3.569335, 3.574218, 3.579101, 3.583984, 3.588867, 3.59375, 3.598632, 3.603515, 3.608398, 3.613281, 3.618164, 3.623046, 3.627929, 3.632812, 3.637695, 3.642578, 3.64746, 3.652343, 3.657226, 3.662109, 3.666992, 3.671875, 3.676757, 3.68164, 3.686523, 3.691406, 3.696289, 3.701171, 3.706054, 3.710937, 3.71582, 3.720703, 3.725585, 3.730468, 3.735351, 3.740234, 3.745117, 3.75, 3.754882, 3.759765, 3.764648, 3.769531, 3.774414, 3.779296, 3.784179, 3.789062, 3.793945, 3.798828, 3.80371, 3.808593, 3.813476, 3.818359, 3.823242, 3.828125, 3.833007, 3.83789, 3.842773, 3.847656, 3.852539, 3.857421, 3.862304, 3.867187, 3.87207, 3.876953, 3.881835, 3.886718, 3.891601, 3.896484, 3.901367, 3.90625, 3.911132, 3.916015, 3.920898, 3.925781, 3.930664, 3.935546, 3.940429, 3.945312, 3.950195, 3.955078, 3.95996, 3.964843, 3.969726, 3.974609, 3.979492, 3.984375, 3.989257, 3.99414, 3.999023, 4.003906, 4.008789, 4.013671, 4.018554, 4.023437, 4.02832, 4.033203, 4.038085, 4.042968, 4.047851, 4.052734, 4.057617, 4.0625, 4.067382, 4.072265, 4.077148, 4.082031, 4.086914, 4.091796, 4.096679, 4.101562, 4.106445, 4.111328, 4.11621, 4.121093, 4.125976, 4.130859, 4.135742, 4.140625, 4.145507, 4.15039, 4.155273, 4.160156, 4.165039, 4.169921, 4.174804, 4.179687, 4.18457, 4.189453, 4.194335, 4.199218, 4.204101, 4.208984, 4.213867, 4.21875, 4.223632, 4.228515, 4.233398, 4.238281, 4.243164, 4.248046, 4.252929, 4.257812, 4.262695, 4.267578, 4.27246, 4.277343, 4.282226, 4.287109, 4.291992, 4.296875, 4.301757, 4.30664, 4.311523, 4.316406, 4.321289, 4.326171, 4.331054, 4.335937, 4.34082, 4.345703, 4.350585, 4.355468, 4.360351, 4.365234, 4.370117, 4.375, 4.379882, 4.384765, 4.389648, 4.394531, 4.399414, 4.404296, 4.409179, 4.414062, 4.418945, 4.423828, 4.42871, 4.433593, 4.438476, 4.443359, 4.448242, 4.453125, 4.458007, 4.46289, 4.467773, 4.472656, 4.477539, 4.482421, 4.487304, 4.492187, 4.49707, 4.501953, 4.506835, 4.511718, 4.516601, 4.521484, 4.526367, 4.53125, 4.536132, 4.541015, 4.545898, 4.550781, 4.555664, 4.560546, 4.565429, 4.570312, 4.575195, 4.580078, 4.58496, 4.589843, 4.594726, 4.599609, 4.604492, 4.609375, 4.614257, 4.61914, 4.624023, 4.628906, 4.633789, 4.638671, 4.643554, 4.648437, 4.65332, 4.658203, 4.663085, 4.667968, 4.672851, 4.677734, 4.682617, 4.6875, 4.692382, 4.697265, 4.702148, 4.707031, 4.711914, 4.716796, 4.721679, 4.726562, 4.731445, 4.736328, 4.74121, 4.746093, 4.750976, 4.755859, 4.760742, 4.765625, 4.770507, 4.77539, 4.780273, 4.785156, 4.790039, 4.794921, 4.799804, 4.804687, 4.80957, 4.814453, 4.819335, 4.824218, 4.829101, 4.833984, 4.838867, 4.84375, 4.848632, 4.853515, 4.858398, 4.863281, 4.868164, 4.873046, 4.877929, 4.882812, 4.887695, 4.892578, 4.89746, 4.902343, 4.907226, 4.912109, 4.916992, 4.921875, 4.926757, 4.93164, 4.936523, 4.941406, 4.946289, 4.951171, 4.956054, 4.960937, 4.96582, 4.970703, 4.975585, 4.980468, 4.985351, 4.990234, 4.995117 }; const static byte chord_table[8][4]PROGMEM = { { 0, 68, 119, 205, },//Maj { 0, 68, 119, 187, },//Maj7 { 0, 68, 119, 239, },//Majadd9 { 0, 34, 119, 205, },//sus2 { 0, 51, 119, 239, },//minadd9 { 0, 51, 119, 170, },//min7 { 0, 51, 119, 205, },//min { 0, 0, 0, 0, }//root }; void setup() { startMozzi(CONTROL_RATE); // :) } void updateControl() { //chord setting chord = (mozziAnalogRead(3) / 128) + (mozziAnalogRead(5) / 128); chord = constrain(chord, 0, 7); //inversion setting inv_knob = mozziAnalogRead(1); inv = (inv_knob / 64)+ (mozziAnalogRead(4) / 64); inv = constrain(inv, 0, 15); if (inv_knob &lt; 1020) { //when selecting wave , not apply switch (inv) { case 0: inv_aply1 = 0; inv_aply2 = 0; inv_aply3 = 0; inv_aply4 = 0; inv_aply5 = 0; break; case 1: inv_aply1 = 1; inv_aply2 = 0; inv_aply3 = 0; inv_aply4 = 0; inv_aply5 = 0; break; case 2: inv_aply1 = 1; inv_aply2 = 1; inv_aply3 = 0; inv_aply4 = 0; inv_aply5 = 0; break; case 3: inv_aply1 = 1; inv_aply2 = 1; inv_aply3 = 1; inv_aply4 = 0; inv_aply5 = 0; break; case 4: inv_aply1 = 1; inv_aply2 = 1; inv_aply3 = 1; inv_aply4 = 1; inv_aply5 = 0; break; case 5: inv_aply1 = 2; inv_aply2 = 1; inv_aply3 = 1; inv_aply4 = 1; inv_aply5 = 0; break; case 6: inv_aply1 = 2; inv_aply2 = 2; inv_aply3 = 1; inv_aply4 = 1; inv_aply5 = 0; break; case 7: inv_aply1 = 2; inv_aply2 = 2; inv_aply3 = 2; inv_aply4 = 1; inv_aply5 = 0; break; case 8: inv_aply1 = 2; inv_aply2 = 2; inv_aply3 = 2; inv_aply4 = 1; inv_aply5 = 1; break; case 9: inv_aply1 = 2; inv_aply2 = 2; inv_aply3 = 1; inv_aply4 = 1; inv_aply5 = 1; break; case 10: inv_aply1 = 2; inv_aply2 = 1; inv_aply3 = 1; inv_aply4 = 1; inv_aply5 = 1; break; case 11: inv_aply1 = 1; inv_aply2 = 1; inv_aply3 = 1; inv_aply4 = 1; inv_aply5 = 1; break; case 12: inv_aply1 = 1; inv_aply2 = 1; inv_aply3 = 1; inv_aply4 = 0; inv_aply5 = 1; break; case 13: inv_aply1 = 1; inv_aply2 = 1; inv_aply3 = 0; inv_aply4 = 0; inv_aply5 = 1; break; case 14: inv_aply1 = 1; inv_aply2 = 0; inv_aply3 = 0; inv_aply4 = 0; inv_aply5 = 1; break; case 15: inv_aply1 = 0; inv_aply2 = 0; inv_aply3 = 0; inv_aply4 = 0; inv_aply5 = 1; break; } } //setting chord note if (inv_knob &lt; 1020) { //when selecting wave , not apply note1 = (pgm_read_byte(&amp;(chord_table[chord][0]))); note2 = (pgm_read_byte(&amp;(chord_table[chord][1]))); note3 = (pgm_read_byte(&amp;(chord_table[chord][2]))); note4 = (pgm_read_byte(&amp;(chord_table[chord][3]))); note5 = (pgm_read_byte(&amp;(chord_table[chord][0]))); } //OSC frequency knob freq1 = mozziAnalogRead(0) / 4 ; //set wave if (inv_knob &gt;= 1020) { //inv knob max wave = (mozziAnalogRead(3) / 128); } //frequency setting voct = mozziAnalogRead(7) ; freqv1 = freq1 * pow(2, (pgm_read_float(&amp;(voctpow[voct + 205 * inv_aply1 + note1])))); //ROOT freqv2 = freq1 * pow(2, (pgm_read_float(&amp;(voctpow[voct + 205 * inv_aply2 + note2])))); //2nd freqv3 = freq1 * pow(2, (pgm_read_float(&amp;(voctpow[voct + 205 * inv_aply3 + note3])))); //3rd freqv4 = freq1 * pow(2, (pgm_read_float(&amp;(voctpow[voct + 205 * inv_aply4 + note4])))); //4th freqv5 = freq1 * pow(2, (pgm_read_float(&amp;(voctpow[voct + note5])))); //ROOT switch (wave) { case 0://saw aSaw1.setFreq(freqv1); // set the frequency aSaw2.setFreq(freqv2); aSaw3.setFreq(freqv3); aSaw4.setFreq(freqv4); aSaw5.setFreq(freqv5); break; case 1://squ aSqu1.setFreq(freqv1); // set the frequency aSqu2.setFreq(freqv2); aSqu3.setFreq(freqv3); aSqu4.setFreq(freqv4); aSqu5.setFreq(freqv5); break; case 2://tri aTri1.setFreq(freqv1); // set the frequency aTri2.setFreq(freqv2); aTri3.setFreq(freqv3); aTri4.setFreq(freqv4); aTri5.setFreq(freqv5); break; case 3://sin aSin1.setFreq(freqv1); // set the frequency aSin2.setFreq(freqv2); aSin3.setFreq(freqv3); aSin4.setFreq(freqv4); aSin5.setFreq(freqv5); break; case 4:// aChb1.setFreq(freqv1); // set the frequency aChb2.setFreq(freqv2); aChb3.setFreq(freqv3); aChb4.setFreq(freqv4); aChb5.setFreq(freqv5); break; case 5:// ahSin1.setFreq(freqv1); // set the frequency ahSin2.setFreq(freqv2); ahSin3.setFreq(freqv3); ahSin4.setFreq(freqv4); ahSin5.setFreq(freqv5); break; case 6:// aSig1.setFreq(freqv1); // set the frequency aSig2.setFreq(freqv2); aSig3.setFreq(freqv3); aSig4.setFreq(freqv4); aSig5.setFreq(freqv5); break; case 7:// aPha1.setFreq(freqv1); // set the frequency aPha2.setFreq(freqv2); aPha3.setFreq(freqv3); aPha4.setFreq(freqv4); aPha5.setFreq(freqv5); break; } } int updateAudio() { switch (wave) { case 0: return MonoOutput::from8Bit(aSaw1.next() / 32 + aSaw2.next() / 32 + aSaw3.next() / 32 + aSaw4.next() / 32 + aSaw5.next() / 32 * inv_aply5); break; case 1: return MonoOutput::from8Bit(aSqu1.next() / 32 + aSqu2.next() / 32 + aSqu3.next() / 32 + aSqu4.next() / 32 + aSqu5.next() / 32 * inv_aply5); break; case 2: return MonoOutput::from8Bit(aTri1.next() / 32 + aTri2.next() / 32 + aTri3.next() / 32 + aTri4.next() / 32 + aTri5.next() / 32 * inv_aply5); break; case 3: return MonoOutput::from8Bit(aSin1.next() / 32 + aSin2.next() / 32 + aSin3.next() / 32 + aSin4.next() / 32 + aSin5.next() / 32 * inv_aply5); break; case 4: return MonoOutput::from8Bit(aChb1.next() / 32 + aChb2.next() / 32 + aChb3.next() / 32 + aChb4.next() / 32 + aChb5.next() / 32 * inv_aply5); break; case 5: return MonoOutput::from8Bit(ahSin1.next() / 32 + ahSin2.next() / 32 + ahSin3.next() / 32 + ahSin4.next() / 32 + ahSin5.next() / 32 * inv_aply5); break; case 6: return MonoOutput::from8Bit(aSig1.next() / 32 + aSig2.next() / 32 + aSig3.next() / 32 + aSig4.next() / 32 + aSig5.next() / 32 * inv_aply5); break; case 7: return MonoOutput::from8Bit(aPha1.next() / 32 + aPha2.next() / 32 + aPha3.next() / 32 + aPha4.next() / 32 + aPha5.next() / 32 * inv_aply5); break; } } void loop() { audioHook(); // required here } </code></pre> <p>(Yeah, it's still a lot...)</p> <p>Any assistance in resolving this would be <em>greatly</em> appreciated!</p>
<p>I don't get a compilation error with your sketch with the latest <a href="https://github.com/sensorium/Mozzi" rel="nofollow noreferrer">git version</a>.</p> <p>If you installed the release version, delete the library in sketchbbok's <code>library</code> folder and download and install the latest git version.</p>
89742
|serial|uart|ch340|
CH340G based USB to UART adapter - Pinouts - Can't find schematics
2022-05-26T22:26:14.910
<p><a href="https://minielektro.dk/dev-10053.html?gclid=CjwKCAjwyryUBhBSEiwAGN5OCIxnaU5lCMS4IczQlnlLFWL2wgJWJj6RQ1qy8xyN4i50NNoEWv6rqBoCLuUQAvD_BwE" rel="nofollow noreferrer">This</a> is the board I will be referring to. <a href="https://i.stack.imgur.com/tgJ9f.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tgJ9f.jpg" alt="Board image" /></a></p> <p>There are different variations of it (with built in buttons etc.) but they all seem to be based on the CH340 chip.</p> <p>My problem is, that I do not know what the pinouts on the board stand for. I cannot find any schematics for the adapter (I can find some for the CH340). Does anyone have a clue as to what the different pins are for?</p>
<p>This module appears to be designed for communicating with the <a href="https://en.wikipedia.org/wiki/ESP8266" rel="nofollow noreferrer">ESP8266 ESP-01</a> board. The pinout for the ESP-01 is shown below, taken from a typical <a href="https://www.microchip.ua/wireless/esp01.pdf" rel="nofollow noreferrer">datasheet</a>:</p> <p><a href="https://i.stack.imgur.com/uycDa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uycDa.png" alt="ESP-01 Pinout" /></a></p> <p>[Updated]The arrow on the CH340 board next to the yellow header indicates the connection orientation. The bulk of the ESP-01 goes on the side of the header pointed to by the arrow, covering the CH340 board, as shown below.</p> <p><a href="https://i.stack.imgur.com/Y4LU2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y4LU2.jpg" alt="connection orientation" /></a></p> <p>Information on the WCH CH340 product set including the G model is <a href="http://www.wch-ic.com/products/CH340.html" rel="nofollow noreferrer">here</a>.</p> <p><a href="https://i.stack.imgur.com/OrWNG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OrWNG.png" alt="CH340G pinout" /></a></p> <p>There is plenty of online information on getting started with the ESP8266 ESP-01 using the Arduino IDE. A good example is at <a href="https://www.instructables.com/Getting-Started-With-Esp-8266-Esp-01-With-Arduino-/" rel="nofollow noreferrer">instructables.com</a>.</p> <p>The other model variations you mentioned (with built in buttons) are probably in response to a known problem with this board when flashing ESP-01s. See <a href="https://www.instructables.com/USB-to-ESP-01-Board-Adapter-Modification/" rel="nofollow noreferrer">here</a> for more info.</p>
89766
|arduino-uno|breadboard|
breadboards and accurate voltage measurments
2022-05-29T12:50:03.810
<p>I am trying to setup a thermistor(PT1000) to work with arduino. For that I used voltage divider and 5V pin as the voltage source. I was getting very unstable results so I removed the thermistor and used 2 1kOhm resistors instead.</p> <p>I was still getting results ranging from very close to true value of 1kOhm to 1.2kOhm. For reference, 4 Ohms are equivalent temperature change of 1 degree celsius.</p> <p>I measured the voltage drop of each resistor and was surprised that it is far from equivalent. Check the video of full setup and the closeup wiring of the voltage divider - <a href="https://easyupload.io/5fctxm" rel="nofollow noreferrer">https://easyupload.io/5fctxm</a></p> <p><a href="https://i.stack.imgur.com/me8y5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/me8y5.png" alt="enter image description here" /></a></p> <p>I cannot explain the 0.3V voltage drop difference between two resistors of the same rating (resistance of 1000 Ohm +-0.5% was verified by multimeter) in any other way but that the breadboard contacts and jump wires are not suitable for accurate voltage measurement. Can someone with more experience confirm if my breadboard is broken or is such behaviour intended.</p>
<p>In order to assess the stability of analog readings on a breadboard, I did an experiment very similar to yours. I plugged two 1 kΩ resistors on a breadboard, connected in series between my Arduino's GND and +5V. I connected the middle point to A0 and made an histogram of one million consecutive calls to <code>analogRead(A0)</code>.</p> <p>Here is my test code:</p> <pre class="lang-cpp prettyprint-override"><code>const int histo_length = 64; const long histo_count = 1000000; long histo[histo_length]; int histo_start; void setup() { Serial.begin(9600); // Center the histogram on the average reading. int sum = 0; for (int i = 0; i &lt; 16; i++) sum += analogRead(A0); int average = sum / 16; histo_start = average - histo_length/2; // Fill the histogram. Serial.println(&quot;Ouliers:&quot;); for (long i = 0; i &lt; histo_count; i++) { int x = analogRead(A0); if (x &gt;= histo_start &amp;&amp; x &lt; histo_start + histo_length) histo[x - histo_start]++; else Serial.println(x); // print oulier } // Print it out. Serial.println(&quot;Histogram:&quot;); for (int i = 0; i &lt; histo_length; i++) { Serial.print(histo_start + i); Serial.print(&quot; &quot;); Serial.println(histo[i]); } } void loop() {} </code></pre> <p>Note that the full histogram would not fit in the memory of my Uno, hence the trick of printing out the outliers instead of recording them.</p> <p>And here is the resulting histogram:</p> <pre><code>508 0 509 39386 510 960567 511 47 512 0 </code></pre> <p>All other histogram bins were empty (no outliers).</p> <p>As you can see, 96% of the calls returned 510. Most of those that did not return 510 returned 509, and less than 0.005% of them returned 511. The RMS dispersion of the readings is about 0.04 ADC steps.</p> <p>I can hardly imagine anything more stable than this.</p>
89768
|signal-processing|
About the FFT library on Arduino
2022-05-29T14:15:02.547
<p>From the output results, i see that the arduinoFFT returns only positive frequencies, thus i think it self removes the negative sided values and compensates the lost energy by multiplying by 2. Is this correct?Ar</p>
<p>I don't know what you mean by a &quot;negative&quot; frequency.</p> <p>FFT takes a set of samples and returns a group of &quot;buckets&quot;, the number of buckets equal to half the number of samples. These buckets cover frequencies from 0Hz to F/2 where F is the sample frequency.</p> <p>Each bucket contains the power magnitude of a block of frequencies in both the real and imaginary &quot;axis&quot; (effectively a pair of coordinates depicting a vector).</p> <p>You compute the absolute power of a bucket through taking the square root of the sum of the squares of the real and imaginary components (basically good ol' pythagoras).</p> <p>This &quot;absolute power&quot; value is the magnitude of a vector. A vector can never have a magnitude &lt; 0. After all, if you have a vector of (1,1) and one of (-1, -1) they are both the same magnitude, just with a different angle (in this example a phase difference of 180 degrees).</p>
89773
|pins|switch|digispark|pinmode|
Safe to solder a slide switch to unused GPIO pins?
2022-05-30T15:18:07.157
<p>I have a Digispark Rev.3 Kickstarter with ATTiny85 (see pinout below) and a three pin slide switch (see example below). I want to use the slide switch to control a task running on the Digispark, with the example code below.</p> <p>The center pin of the slide switch will be connected to GND, one pin will be soldered to pin 2 on the Digispark (<code>pinMode(2, INPUT_PULLUP);</code>) and the remaining pin will be unused.</p> <p>To install the switch, I want to have the center pin of the switch go through P3 on the pinout, one pin through P2 (which will be addressed in the code) and the remaining pin through P4. This means, P3 will be soldered to GND and depending on the switches position, P2 or P4 will connect to GND as well.</p> <p>Could these connections between P2, P3 or P4 and GND interfere with the functionality or damage the Digispark?</p> <pre><code>int switchPos; void setup() { pinMode(2, INPUT_PULLUP); } void loop() { switchPos = digitalRead(2); if (sensorVal == HIGH) { runCode(); } else { delay(1000); } } </code></pre> <p><a href="https://i.stack.imgur.com/lPmI2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lPmI2.png" alt="Digispark Rev.3 Kickstarter with ATTiny85" /></a> <a href="https://i.stack.imgur.com/LGfhL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LGfhL.jpg" alt="Three pin slide switch" /></a></p>
<p>Yes, you will lose the USB connection, since PB3 and PB4 are used for the USB communication. Normally you wouldn't solder a component directly onto a board if it doesn't fit with all pins. Instead you would use wires or a breakout PCB to do the job.</p> <p>If you really want to to that and you don't need any of the other pins, then you can use PB0 and PB1. Set PB1 to OUTPUT LOW and PB0 as input. The OUTPUT LOW is basically the same as ground and configuring a pin as INPUT will make it high resistance, so it doesn't interfere with the circuit.</p>
89776
|arduino-mega|c++|
How to shift binary into a shift register (serial in, parallel out) sequentially
2022-05-30T23:20:39.207
<p>I'm trying to make a continuity tester at work where I connect the input and output of a harness into a test fixture powered by an Arduino. This tester tests whether the position of the connects are pinned correctly.</p> <p>Here is the diagram of my initial idea:</p> <p><a href="https://i.stack.imgur.com/NKgVm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NKgVm.png" alt="enter image description here" /></a></p> <p>From one end of the connector (the output in the diagram), I want to shift in a binary that is in the power of 2. For instance, shifting in <code>0001</code>, check for continuity by reading the 75HC165 (parallel in, serial out), then clear the register and then shift in <code>0010</code>, and then <code>0100</code> and so on. For a correctly pinned harness, the write and read binary subtraction will be zero.</p> <p>Here is my loop that attempts to perform the above:</p> <pre><code>void loop() { for (int i = 1; i &lt; 4; i++) { reset_SIPO_register(); shift_SIPO(pow(2,i)); delay(2000); shift_SIPO(0x00)); check_continuity(); // not implemented yet } } void reset_SIPO_register() { digitalWrite(reset_pin, LOW); digitalWrite(reset_pin, HIGH); } void shift_SIPO(int sequence) { digitalWrite(latch_pin, LOW); shiftOut(data_pin, clock_pin, MSBFIRST, sequence); digitalWrite(latch_pin, HIGH); } </code></pre> <p>I am testing this concept on a breadboard with LEDs and the above kind of works. However, the LED is lit up one at a time and they don't turn off, not following the binary.</p> <p>Is there something I'm missing here? thanks!</p>
<p>Do not use <code>pow()</code>. This is a function that works with floating point numbers. It is roughly equivalent (for y &gt; 0) to</p> <pre class="lang-cpp prettyprint-override"><code>double pow(double x, double y) { return exp(y * log(x)); } </code></pre> <p>As all transcendental functions, its implementation is prone to rounding errors. It is not even guaranteed to give you the “correctly” rounded version of the exact (i.e. infinite precision) result. In fact, very few floating point functions give this guarantee.</p> <p>As an example, if you compute <code>pow(2, i)</code> for i = 3, you get 7.9999980926513671875. This is 4 <a href="https://en.wikipedia.org/wiki/Unit_in_the_last_place" rel="nofollow noreferrer">ULPs</a> smaller than the exact value. Passing this number to <code>shift_SIPO()</code> implicitly converts it to an <code>int</code>, and this conversion always rounds to zero. Thus you get 7, i.e. <code>0b0111</code>.</p> <p>What you want is an integer, exact implementation of <code>pow(2, i)</code>. It turns out this is quite simple: Take the integer 1 in binary, then shift it <code>i</code> times to the left. That is</p> <pre class="lang-cpp prettyprint-override"><code>shift_SIPO(1 &lt;&lt; i); </code></pre>
89808
|esp8266|i2c|io-expander|
ESP8266 soft resets when using a GPIO Expander
2022-06-02T16:43:24.793
<p>In my project I'm trying to use a PCF8574 to drive some peripherals, since the ESP8266 doesn't offer all the GPIO pins I need, however I seem to be having problems at the most basic level of driving the pins of an e-paper display.</p> <p>The e-paper display is connected to MOSI, MISO and SCL to the &quot;native&quot; pins GPIO12, 13 and 14, and I wanted to rely on the PCF to drive the other four pins (CS, DC, RST, BUSY).</p> <p>I modified <a href="https://github.com/waveshare/e-Paper/tree/master/Arduino/epd4in2" rel="nofollow noreferrer">the original library</a> so that it could accept an arbitrary <code>Pin</code> abstraction that looks like the following:</p> <pre class="lang-cpp prettyprint-override"><code>class Pin { public: Pin(void){}; ~Pin(void){}; virtual uint8_t read() = 0; virtual void write(uint8_t value) = 0; }; </code></pre> <p>and at first implemented it as <code>ArduinoPin</code>, which all it does is setting up the pin mode and calling <code>digitalRead</code> or <code>digitalWrite</code> when needed.</p> <p>While connecting the EPD with the <code>ArduinoPin</code> implementation, using D0, D1, D2, D4 as pins, the e-paper display works correctly, so I proceeded to make another implementation of Pin with the GPIO Expander.</p> <p>Following the GPIO Expander and relative Pin implementations</p> <p><code>gpio-expander.h</code></p> <pre class="lang-cpp prettyprint-override"><code>class GpioExpander { public: GpioExpander(uint16_t address); GpioExpander(); uint8_t read(uint8_t pin); void write(uint8_t pin, uint8_t value); private: uint8_t buffer[1] = {0xFF}; uint16_t address; }; class GpioExpanderPin : public Pin { public: GpioExpanderPin(GpioExpander *expander, uint8_t pinNumber); ~GpioExpanderPin(void); virtual uint8_t read(); virtual void write(uint8_t value); private: uint8_t myPin; GpioExpander *expander; }; </code></pre> <p><code>gpio-expander.cpp</code></p> <pre class="lang-cpp prettyprint-override"><code>GpioExpander::GpioExpander(uint16_t address) { this-&gt;address = address; buffer[0] = 0xFF; Wire.beginTransmission(address); Wire.write(buffer[0]); Wire.endTransmission(); } GpioExpander::GpioExpander() : GpioExpander(0x20) {} uint8_t GpioExpander::read(uint8_t pin) { write(pin, 1); Wire.requestFrom(address, 1); buffer[0] = Wire.read(); return (buffer[0] &gt;&gt; pin) &amp; 1; } void GpioExpander::write(uint8_t pin, uint8_t value) { if (value == 1) buffer[0] |= (1 &lt;&lt; pin); else buffer[0] &amp;= ~(1 &lt;&lt; pin); Wire.beginTransmission(address); Wire.write(buffer[0]); Wire.endTransmission(); } </code></pre> <p><code>gpio-expander-pin.cpp</code></p> <pre class="lang-cpp prettyprint-override"><code>GpioExpanderPin::GpioExpanderPin(GpioExpander *expander, uint8_t pinNumber) { this-&gt;expander = expander; myPin = pinNumber; } GpioExpanderPin::~GpioExpanderPin(void) {} uint8_t GpioExpanderPin::read() { return this-&gt;expander-&gt;read(myPin); } void GpioExpanderPin::write(uint8_t value) { this-&gt;expander-&gt;write(myPin, value); } </code></pre> <p>These implementations work fine, I tested everything with a multimeter and I can arbitrarily write 1s and 0s on all 8 pins of the PCF, but when I try to drive the four pins of the e-paper, the ESP8266 resets and I have no clue on why. I tried with the exception decoder and the following stacktrace appears:</p> <pre><code>Exception Cause: Not found 0x40202984: Twi::read_bit() at ??:? 0x402029db: Twi::write_byte(unsigned char) at ??:? 0x40202b94: Twi::writeTo(unsigned char, unsigned char*, unsigned int, unsigned char) at ??:? 0x40202bb9: Twi::writeTo(unsigned char, unsigned char*, unsigned int, unsigned char) at ??:? 0x40202cc0: twi_writeTo at ??:? 0x40201720: TwoWire::endTransmission(unsigned char) at ??:? 0x40105cfe: os_printf_plus at ??:? 0x40201748: TwoWire::endTransmission() at ??:? 0x402017f5: GpioExpander::write(unsigned char, unsigned char) at ??:? 0x40201794: GpioExpanderPin::write(unsigned char) at ??:? 0x402011f9: Epd::spiTransfer(unsigned char) at ??:? 0x40201238: Epd::sendData(unsigned char) at ??:? 0x40201385: Epd::clear() at ??:? 0x402010b6: setup at ??:? 0x4020583c: std::_Function_handler&lt;bool (), settimeofday::{lambda()#1}&gt;::_M_manager(std::_Any_data&amp;, std::_Function_handler&lt;bool (), settimeofday::{lambda()#1}&gt; const&amp;, std::_Manager_operation) at time.cpp:? 0x4020583c: std::_Function_handler&lt;bool (), settimeofday::{lambda()#1}&gt;::_M_manager(std::_Any_data&amp;, std::_Function_handler&lt;bool (), settimeofday::{lambda()#1}&gt; const&amp;, std::_Manager_operation) at time.cpp:? 0x4020583c: std::_Function_handler&lt;bool (), settimeofday::{lambda()#1}&gt;::_M_manager(std::_Any_data&amp;, std::_Function_handler&lt;bool (), settimeofday::{lambda()#1}&gt; const&amp;, std::_Manager_operation) at time.cpp:? 0x4020583c: std::_Function_handler&lt;bool (), settimeofday::{lambda()#1}&gt;::_M_manager(std::_Any_data&amp;, std::_Function_handler&lt;bool (), settimeofday::{lambda()#1}&gt; const&amp;, std::_Manager_operation) at time.cpp:? 0x40202158: loop_wrapper() at core_esp8266_main.cpp:? 0x40100e85: cont_wrapper at ??:? </code></pre> <p>(Not sure why I can't get the source lines to appear, any suggestion in that is most welcome.)</p> <p>Anyway apparently the problem appears when ending the I2C transmission, at the lowest level possible, at Twi::read_bit, which I include for the sake of all of you trying to help me out</p> <p><code>core_esp8266_si2c.cpp</code></p> <pre class="lang-cpp prettyprint-override"><code>bool Twi::read_bit(void) { SCL_LOW(twi_scl); SDA_HIGH(twi_sda); busywait(twi_dcount + 2); SCL_HIGH(twi_scl); WAIT_CLOCK_STRETCH(); bool bit = SDA_READ(twi_sda); busywait(twi_dcount); return bit; } </code></pre> <p>The most upsetting thing is that this same setup, when programmed in Micropython works just fine (I can't use Micropython though, because I need all the RAM I can get from the ESP to draw pictures, and I'm much interested in the overall performance I can get with C++).</p> <p>Anyone had this same problem? Any advice on how to fix this behavior?</p> <p><strong>EDIT</strong></p> <p>With some experimentation, I managed to replicate the problem in a smaller scale. The following code resets the ESP8266 as well:</p> <pre class="lang-cpp prettyprint-override"><code>void setup() { Wire.begin(); GpioExpander expander; GpioExpanderPin pin(&amp;expander, 0); while(true) { pin.write(0); pin.write(1); } } </code></pre> <p>It looks like fast cycles of on-off crash the system (which is what the EPD library does when sending data, turning on and off the pins relatively fast to switch between modes etc.). Not sure how to address this though, but I believe it might be something related to the Twi libraries at this point.</p> <p><strong>EDIT 2</strong></p> <p>Adding a <code>yield()</code> to the <code>write</code> function of the gpio expander class makes the issue go away, but the time to execute a simple display clear grows to unacceptable levels (~3 seconds to perform a full display refresh).</p> <p>Any suggestion is appreciated at this point.</p> <p><strong>EDIT 3</strong></p> <p>I did some more experimenting and benchmarking, and reached the following conclusions:</p> <ul> <li>the time that it takes for the Wire library to send data to the GPIO expander (the <code>write</code> function) is ~50µs</li> <li>when using the gpio expander, the time to write data to the SPI device (DC write + enable CS + SPI transfer + disable CS) takes a total of ~170µs (which checks out, 3 times calling the gpio expander makes for ~150µs and the rest is SPI transaction)</li> <li>when using the arduino pins, the time to write data to the SPI device takes ~10µs (an order of magnitude less than the GPIO expander).</li> </ul> <p>To send a total of 150,000 bytes to the e-paper display, then, with the GPIO expander takes roughly 3 seconds, while with the normal pins it would take 10 times less (0.3 seconds). The reset issue is surely due to the time spent in the send loop: the watchdog thinks the program is stuck in an infinite loop and thus resets the board. This is why the calls to <code>yield</code> remove the reset issues.</p> <p>I believe I must either find a faster implementation of wire (?) or try to minimize usage of CS / DC pins</p>
<p>In the end the answer to the problem is the update frequency of the pins that drive the e-paper display:</p> <p>The original waveshare library (as linked in the post) does the following to send data to the EPD:</p> <ul> <li>enable DC (to tell the EPD that it's receiving DATA)</li> <li>enable CS (to tell the EPD to listen to the incoming SPI data)</li> <li>send SPI data</li> <li>disable CS (to tell the EPD that anything received after that is not its competence)</li> </ul> <p>Normally with arduino's <code>digitalWrite</code> this happens in a matter of ~10µs, and even if we repeat this process 15k times (that's how many bytes a 4.2 inch display supports) we spend 0.15 seconds to update <strong>half</strong> of the display's content (because the EPD has 2 memory banks which must be written).</p> <p>When using the GPIO expander, instead, the mean time to send data via I2C is something around 50µs, which means that to enable / disable the pins three times we increase tenfold the time that the normal digital write takes (~150µs) which translates to 1.5 seconds to update half of the display and finally roughly 3 seconds for a full update.</p> <p>During this loop, the watchdog thinks that the program is stalling and resets the chip. This is why using <code>yield</code> the update runs its course correctly.</p> <p>To fix this issue, I worked on the EPD library and reduced the use of the digital writes, by creating a &quot;session&quot; of sorts: whenever I start writing data in a loop, I enable the CS pin, and disable it only at the end of the loop, so that the 100µs are only expended around the data transfer loop.</p> <p>This is actually what happened in the Micropython driver for the e-paper display: the SPI connection sent data in chunks, enabling and disabling the chip select pin only at the beginning and end of the &quot;transaction&quot;.</p> <p>I'm planning to publish the updated library at some point, once everything is smoothed out, if this can interest anyone leave a message :)</p>
89810
|sim800|
SIM800L stays in 1sec-blink-state
2022-06-03T04:56:41.563
<p>I've bought such on Amazon. My main problem is that it stays in 1sec-blink, meaning it can't registrer cellular network.</p> <p>First I tried with all anntennas possiblities (one of each, both, none) - failed.</p> <p>Using NodeMCU (for 3.3 TxRx) and <code>SoftwareSerial.h</code> to communicate. It answers all AT command as expected.</p> <p>I tried several powering possibilities (as noted extensively about 2A on the internet), including 18650 , 2000mAh battery connected only to SIM800L module with no MCU connected, still same state.</p> <p>What Can be done else?</p> <p>SEE PELEPHONE: <a href="https://i.stack.imgur.com/mWCzC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mWCzC.png" alt="Carrier support - &quot;PELEPHONE&quot;" /></a></p>
<p>Your mobile network provider does not provide a 2G (GPRS / GSM) network.</p> <p>2G is graduallly being phased out around the globe, so switching to an LTE modem is really the way forward.</p> <p>If you still want to use the SIM800L then you need a network provider that gives 2G services. Fortunately the SIM800L is a &quot;quad band&quot; modem, so it will work with pretty much any 2G provider (it works on 850/900/1800/1900MHz, hence the &quot;quad&quot; of &quot;quad band&quot;).</p>
89815
|esp32|variables|memory|
Wrong use of memory?
2022-06-04T07:01:03.780
<p>Probably I'm doing something wrong. I'm writing an Arduino sketch for ESP32. Among the others I have this function:</p> <pre><code>#define HDR_MAX_LENGHT 4 #define CMD_MAX_LENGHT 5 #define ARG_MAX_LENGHT 5 #define ARG_MAX_NUMBER 8 void ProcessLine(HardwareSerial *serial, char *line) { int ret; int argc; char header[HDR_MAX_LENGHT + 1]; char cmd[CMD_MAX_LENGHT + 1]; char argv[ARG_MAX_NUMBER][ARG_MAX_LENGHT + 1]; return; // for debugging } </code></pre> <p>Usage example:</p> <pre><code>void loop() { static char inBuf[64]; if (Serial.available()) { size_t size = Serial.readBytes(inBuf, 64); inBuf[size] = '\0'; ProcessLine(&amp;Serial, inBuf); } } </code></pre> <p>In the last days all worked fine. After adding other code, I noticed that sometimes my program &quot;hangs&quot;: nothing runs. Perhaps it goes in an exception trap.</p> <p>Commenting out the different sections of the code, I discovered that if I remove the declarations of the variables in <code>ProcessLine()</code> no more hangs happen. The current RAM consumption is negligible: 0.5%.</p> <p>During the tests NO serial data was received! So the function <code>ProcessLine()</code> was <em>never</em> called. Hence, only the declaration of the variables lead to the &quot;hang&quot;.</p> <p>I wonder if there are some mistakes in the code above. Otherwise, how I can further debug my code to understand what I've done wrong?</p>
<p>As I said in a comment, there is nothing wrong with these declarations. Now, here are some debugging strategies you may try:</p> <ol> <li><p>You can rebuild your program with all compiler warnings enabled. Look carefully at the compiler messages and investigate any warning you see.</p> </li> <li><p>You can continue with your current strategy: put back those declarations, then try to remove something else. You may find that there are multiple pieces of code that, when removed, make your program work again. Chances are the problem resides in one of those pieces. But then, it may be that the problem is in the interaction between multiple pieces rather than in one specific piece.</p> </li> <li><p>You may just read the code carefully and see if you spot something suspicious. This can work sometimes: see how @Juraj spotted a buffer overflow in your code snippet just by reading it.</p> </li> <li><p>You can add debug messages across your program, to check what branches are executed, the values of variables...</p> </li> <li><p>I don't know the ESP32 dev environment, but you can check whether the compiler supports adding “sanitizers”. These are pieces of code added by the compiler that do run-time checks on your program, and report problems as they happen. You may want to enable at least an address sanitizer and an undefined behavior sanitizer.</p> </li> <li><p>If the environment supports it, you can try to run the program in a debugger. No success guaranteed: if the program corrupts its memory, it may crash in some place unrelated to the actual problem. The debugger will tell you where it crashed, which may not be very helpful in this case.</p> </li> <li><p>If the ESP dev environment supports neither 5 nor 6, you may try to run your program on your PC. There are a couple of Arduino-compatible cores that you can download for running on a PC.</p> </li> </ol>
89825
|library|platformio|
Create a library when using PlatformIO
2022-06-05T13:53:29.397
<p><strong>(1)</strong> I'm trying to work with libraries in PlatformIO format&quot;, for <a href="https://i.stack.imgur.com/lq1ad.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lq1ad.png" alt="example" /></a>, of a library, located in Arduino's <code>libraries</code>, where code is llocated under <code>\src</code> directry.</p> <p><strong>(2)</strong> Any other library, not it &quot;PlatformIO format&quot; as I call it, has to contain inside <code>libraries/EXMPLE</code> lib a <code>EXMPLE.h</code>, and <code>EXMPLE.cpp</code> file.</p> <p><strong>(3)</strong> Now, when I try to create a &quot;PlatromIO format&quot; library (since I want to move to PlatfromIO) compilation fails, saying <code>.h</code> file was not found (an error you would get since <code>.h</code> <code>.cpp</code> was not located in their parent directory), as noted in <strong>2</strong> . see library <code>ABCD</code> in <a href="https://i.stack.imgur.com/uFoBt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uFoBt.png" alt="snapshot" /></a> (which contains only library structures).</p> <p>Appreciate any help</p> <p>Guy</p>
<p>You're describing &quot;1.5.x&quot; format libraries, not &quot;PlatformIO&quot;. This arrangement for a library was created for Arduino IDE version 1.5.0.</p> <p>The critical part of this library format is the <code>library.properties</code> file which describes the library, and also identifies it as being a library (and which you seem to be lacking). The format of the file is described <a href="https://arduino.github.io/arduino-cli/0.20/library-specification/" rel="nofollow noreferrer">here</a>.</p>
89834
|arduino-uno|serial|raspberrypi|arduino-cli|
Error while uploading the sketch to Arduino UNO using CLI
2022-06-06T17:45:34.950
<p>I have connected my Arduino UNO through USB to Raspberry pi 3B. I am using CLI for editing, compiling and uploading sketches &gt; <code>arduino-cli upload --fqbn arduino:avr:uno cli-test</code>. However, after attempting to upload the sketch, it throws the error, <code>Error during Upload: Failed uploading: no upload port provided</code> I even checked if the Arduino is detected on the respective port using <code>arduino-cli board list</code> and it shows</p> <pre><code>/dev/ttyACM0 serial Serial Port (USB) Arduino Uno arduino:avr:uno arduino:avr /dev/ttyAMA0 serial Serial Port Unknown </code></pre> <p>The <a href="https://support.arduino.cc/hc/en-us/articles/360020831120-Error-2-UNKNOWN-uploading-error-no-upload-port-provided" rel="nofollow noreferrer">support forum</a> of Arduino says to 'select' the port. Nevertheless the support forum resolves the error for GUI application and not for CLI. I searched for how to select the port in CLI, but in vain. Any help is appreciated.</p>
<p>You specify the port with the <code>--port</code> flag to the upload command:</p> <pre class="lang-bash prettyprint-override"><code>$ arduino-cli upload --fqbn arduino:avr:uno --port /dev/ttyACM0 cli-test </code></pre> <p>You can find all these things out for yourself by using <code>--help</code> at any time. For example:</p> <pre class="lang-bash prettyprint-override"><code>$ arduino-cli upload --help Upload Arduino sketches. This does NOT compile the sketch prior to upload. Usage: arduino-cli upload [flags] Examples: arduino-cli upload /home/user/Arduino/MySketch Flags: --board-options strings List of board options separated by commas. Or can be used multiple times for multiple options. --discovery-timeout duration Max time to wait for port discovery, e.g.: 30s, 1m (default 1s) -b, --fqbn string Fully Qualified Board Name, e.g.: arduino:avr:uno -h, --help help for upload --input-dir string Directory containing binaries to upload. -i, --input-file string Binary file to upload. -p, --port string Upload port address, e.g.: COM3 or /dev/ttyACM2 -P, --programmer string Programmer to use, e.g: atmel_ice -l, --protocol string Upload port protocol, e.g: serial -t, --verify Verify uploaded binary after the upload. Global Flags: --additional-urls strings Comma-separated list of additional URLs for the Boards Manager. --config-file string The custom config file (if not specified the default will be used). --format string The output format for the logs, can be: text, json, jsonmini, yaml (default &quot;text&quot;) --log-file string Path to the file where logs will be written. --log-format string The output format for the logs, can be: text, json --log-level string Messages with this level and above will be logged. Valid levels are: trace, debug, info, warn, error, fatal, panic --no-color Disable colored output. -v, --verbose Print the logs on the standard output. </code></pre>
89843
|esp32|uploading|error|platformio|vscode|
esp32, platformio A fatal error occurred: Packet content transfer stopped (received 8 bytes) *** [upload] Error 2
2022-06-07T14:46:19.247
<p>When i try to upload code to the esp32 the following error shows up in the command line:</p> <p><strong>A fatal error occurred: Packet content transfer stopped (received 8 bytes).</strong></p> <p>I use platformio in VScode the platform.ini file looks like this:</p> <pre><code> [env:esp-wrover-kit] platform = espressif32 board = esp-wrover-kit framework = arduino upload_port = COM4 monitor_speed = 115200 </code></pre> <p>Here's the code i'm trying to upload:</p> <pre><code>#include &lt;Arduino.h&gt; void setup() { Serial.begin(115200); Serial.println(&quot;init&quot;); } void loop() { } </code></pre> <p>It's an esp32-wrover-dev from freenove. When i unplug it and plug it back in it starts to write random stuff to the serial monitor, when i attempt an upload it stops but it also gives me the error above.</p>
<p>I had this error when trying to upload a sketch from Arduino IDE to a TTGO T-Display, found that I could resolve this by changing the upload speed from the default of 921600 to 115200.</p> <p>After doing that it uploaded just fine with no issues.</p>
89844
|esp32|web-server|spiffs|
ESP32 AsyncWebServer with softAP does not serve pages
2022-06-07T16:11:40.440
<p>I'm trying to create a <code>AsyncWebServer</code> after enabling the <code>SoftAP</code>:</p> <pre><code>#include &lt;Arduino.h&gt; #include &lt;SPIFFS.h&gt; #include &lt;WiFi.h&gt; #include &lt;WiFiAP.h&gt; #include &lt;AsyncTCP.h&gt; #include &lt;ESPAsyncWebServer.h&gt; WebApp webapp; void setup() { Serial.begin(115200); SPIFFS.begin(); File f = SPIFFS.open(&quot;/index.html&quot;); String s = f.readString(); Serial.println(s); f.close(); WiFi.softAP(&quot;ssid&quot;, NULL); WiFi.softAPsetHostname(&quot;ssid&quot;); Serial.println(WiFi.softAPIP()); webapp.Begin(); } void loop() { } class WebApp { public: WebApp(); void Begin(); private: AsyncWebServer _server; }; #include &quot;webapp.h&quot; WebApp::WebApp() : _server(80) { } void WebApp::Begin() { _server.on(&quot;/&quot;, HTTP_GET, [this](AsyncWebServerRequest *request) { Serial.println(&quot;GET request&quot;); _server.serveStatic(&quot;/&quot;, SPIFFS, &quot;/&quot;).setDefaultFile(&quot;/index.html&quot;); }); _server.onNotFound([](AsyncWebServerRequest *request){ request-&gt;send(404); }); _server.begin(); Serial.println(&quot;[WEB] HTTP server started&quot;); } </code></pre> <p>The <code>SoftAP</code> brings up the network and I can connect to it (<code>softAPgetStationNum()</code> tells me that 1 client is connected). It answers to pings. The <code>index.html</code> is stored into the flash (the contents is printed out correctly).</p> <p>But when I try to open the root page (192.168.4.1) it prints out &quot;GET request&quot; but the browser request timeouts and nothing is received.</p> <p>Am I missing anything in the code?</p>
<p>The usage of <code>serveStatic()</code> is wrong. It's not intended to be used inside a callback. Just place the call in the setup of the webserver, i.e.:</p> <pre><code>void WebApp::Begin() { _server.serveStatic(&quot;/&quot;, SPIFFS, &quot;/&quot;).setDefaultFile(&quot;/index.html&quot;); _server.onNotFound([](AsyncWebServerRequest *request) { request-&gt;send(404); }); _server.begin(); Serial.println(&quot;[WEB] HTTP server started&quot;); } </code></pre>
89845
|arduino-uno|memory-usage|compiler|
How to make the compiler ensure that local variables memory allocation won't cause any RAM overflow during execution?
2022-06-07T16:38:03.623
<p>Upon compiling a sketch using the Arduino IDE, a message like the following gets displayed in the console:</p> <pre><code>Global variables use 1540 bytes (75%) of dynamic memory, leaving 508 bytes for local variables. Maximum is 2048 bytes. </code></pre> <p>In addition, it seems that if the global variables use exceeds around 75% of total dynamic memory, the following message gets displayed in addition:</p> <pre><code>Low memory available, stability problems may occur. </code></pre> <p>So, it seems that by using the IDE in a regular way, the compiler does not ensure that local variables memory allocation won't cause any RAM overflow during program execution. Instead, it just displays a warning message when little RAM is left for local variables.</p> <p>This can lead to program malfunctions at execution time, if local variables happen to take up more space than the remaining RAM.</p> <p>How can one have the compiler detect whether local variables memory allocation will cause RAM overflow during execution or not, and warn the user at compile time only in those specific cases?</p>
<p>You are describing &quot;memory profiling&quot; and is not typically a feature of C or C++. It is more common in higher level languages, such as Java, but C is a considered a much lower level language.</p> <p>Typically such profiling is done at runtime using external tools such as <code>valgrind</code> and <code>massif</code>.</p> <p>It's not really possible for the compiler to work out what your program will be doing when it is using external data and inputs to control how it works. Any such tests at compile time would be pretty much meaningless since any that pass in testing may still cause problems at runtime depending on what else may be happening at the same time, or even what may have happened in the past (see <a href="https://cpp4arduino.com/2018/11/06/what-is-heap-fragmentation.html" rel="nofollow noreferrer">heap fragmentation</a>).</p>
89864
|arduino-uno|c++|
How to convert a reading to percentage in Arduino
2022-06-09T17:07:00.783
<p>I am using <a href="http://developer.wildernesslabs.co/Hardware/Tutorials/Electronics/Part5/Resistive_Sensor_Lab/" rel="nofollow noreferrer">this example</a> on how to use a photoresistor to detect the value of light that the sensor is getting but I want to convert the reading of the resistor to a percentage but I can't use the <code>map()</code> function from the Arduino <a href="https://www.arduino.cc/reference/en/language/functions/math/map/" rel="nofollow noreferrer">docs</a> but I can implement something similar to it</p> <p>so I created this simple function</p> <pre><code>float photo_resistor(int pinNum) { float reading = analogRead(pinNum); if (reading == 54) { return 0.0; } return (reading - 54)/(100/920); } </code></pre> <p>as in the docs I want to use an output range from 0 to 100 and the minimum reading i got is 54 and the maximum is 974</p> <pre><code>return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; // this becomes (x - 54)*(100 - 0 ) / ( 974 - 54) + 0; // (x-54)/(100/920); </code></pre> <p>but this does not output a value from on the scale from 0-100</p> <p><a href="https://i.stack.imgur.com/DnoNl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DnoNl.png" alt="enter image description here" /></a></p>
<p>You wrote:</p> <blockquote> <pre class="lang-cpp prettyprint-override"><code>return (reading - 54)/(100/920); </code></pre> </blockquote> <p>In C++, <code>100/920</code> is zero. This is because, when both operands are integers, the division operator performs an integer division. You can overcome this problem by making sure that at least one of the operands is a floating point number. For instance, <code>100.0/920</code> is roughly 0.1087.</p> <p>However, your division is backwards. You probably mean</p> <pre class="lang-cpp prettyprint-override"><code>return (reading - 54) * (100.0/920); </code></pre>
89868
|arduino-nano|library|
TVout characters don't line up
2022-06-10T06:37:14.970
<p>I am messing around with the Arduino TVout library and I have created some multi-character tiles (I don't know what else to call them). Just to start out, I created a simple X that spans across 4 characters but when I print them to the screen they align correctly.</p> <p>How they should align:<br /> <img src="https://i.stack.imgur.com/j4XMt.png" /></p> <p>How they really align:<br /> <img src="https://i.stack.imgur.com/hccNk.jpg" width="200" /></p> <p>Here is the code I have so far:</p> <p>Main file:</p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;expressions.h&quot; #include &lt;TVout.h&gt; TVout win; unsigned char x = 0, y = 0; void setup() { win.begin(NTSC); win.select_font(expr8x8); } void loop() { win.clear_screen(); x = 2, y = 5; print_char(0, x, y); win.delay(1); } void print_char(char c, int startx, int starty) { int tmpx = startx, tmpy = starty; for (char i = c; i &lt; c + 4; i++) { win.print_char(tmpx * 8, tmpy * 8, i); if (++tmpx == c + 2) { tmpy++; tmpx = startx; } } } </code></pre> <p>expressions.h</p> <pre><code>#define EXPRESSIONS8x8_H #include &lt;avr/pgmspace.h&gt; extern const unsigned char expr8x8[]; </code></pre> <p>expressions.cpp</p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;expressions.h&quot; PROGMEM const unsigned char expr8x8[] = { 8, 8, 0, // width, height, start // broken 0x00, 0x00, 0x30, 0x38, 0x1c, 0x1e, 0x07, 0x03, 0x00, 0x00, 0x0c, 0x1c, 0x38, 0x70, 0xe0, 0xc0, 0x03, 0x07, 0x0e, 0x1c, 0x38, 0x38, 0x00, 0x00, 0xc0, 0xc0, 0x70, 0x38, 0x1c, 0x0c, 0x00, 0x00, // happy 0x00, 0x00, 0x00, 0x00, 0x07, 0x1f, 0x38, 0x70, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xf8, 0x1c, 0x0e, 0x60, 0x60, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x06, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00 }; </code></pre> <p>Is there something I am doing wrong? How do I fix this bug/issue?</p>
<p>I believe your problem is in this line:</p> <pre class="lang-cpp prettyprint-override"><code>if (++tmpx == c + 2) { </code></pre> <p>Here you are mixing two different things:</p> <ul> <li><code>c</code> is a character code, i.e. the index of a glyph within the <code>expr8x8</code> font</li> <li><code>tmpx</code> is the index of a character cell (a 8×8 block of pixels) within a line of the screen</li> </ul> <p>Comparing those makes little sense. And in fact, the comparison will always be false, as <code>c</code> is zero, and <code>tmpx</code> starts at 2 and increases from there.</p> <p>I guess what you meant was:</p> <pre class="lang-cpp prettyprint-override"><code>if (++tmpx == startx + 2) { </code></pre>
89871
|arduino-uno|i2c|
Why are raw data bytes not converting to ASCII, but only in one part of my program?
2022-06-10T18:21:55.237
<p>I am writing a program to read from the Atlas Scientific EZO-HUM, -O2, and -CO2 sensors simultaneously via the I2C protocol with an Arduino Uno. The sensors all work, but for some reason, just the O2 sensor data does not convert to ASCII text. Below is my program:</p> <pre><code>#include &lt;Ezo_i2c.h&gt; #include &lt;Ezo_i2c_util.h&gt; #include &lt;iot_cmd.h&gt; #include &lt;sequencer1.h&gt; #include &lt;sequencer2.h&gt; #include &lt;sequencer3.h&gt; #include &lt;sequencer4.h&gt; #include &lt;Wire.h&gt; //enable I2C. #define HUM_address 111 //default I2C ID number for EZO Humidity sensor. #define O2_address 108 //default I2C ID number for EZO O2 sensor. #define CO2_address 105 //default I2C ID number for EZO CO2 sensor. //EZO-HUM vars // | | // V V char computerdata[32]; //we make a 32 byte character array to hold incoming data from a pc/mac/other. byte received_from_computer = 0; //we need to know how many characters have been received. byte serial_event = false; //a flag to signal when data has been received from the pc/mac/other. byte code = 0; //used to hold the I2C response code. char Humidity_data[22]; //we make a 22-byte character array to hold incoming data from the Humidity sensor. byte in_char = 0; //used as a 1 byte buffer to store inbound bytes from the Humidity sensor. byte i = 0; //counter used for Humidity_data array. int time_ = 1000; //used to set the delay needed to process the command sent to the EZO Humidity sensor. //EZO-CO2 vars // | | // V V //char CO2_computerdata[20]; //we make a 20 byte character array to hold incoming data from a pc/mac/other. byte CO2_received_from_computer = 0; //we need to know how many characters have been received. byte CO2_serial_event = false; //a flag to signal when data has been received from the pc/mac/other. byte CO2_code = 0; //used to hold the I2C response code. char CO2_data[20]; //we make a 20-byte character array to hold incoming data from the Co2 sensor. byte CO2_in_char = 0; //used as a 1 byte buffer to store inbound bytes from the Co2 sensor. byte CO2_i = 0; //counter used for Co2_data array. //int CO2_time_ = 1000; //used to set the delay needed to process the command sent to the EZO Co2 sensor. int Co2_int; //int var used to hold the value of the Co2. //EZO-O2 vars // | | // V V //char O2_computerdata[20]; //we make a 20 byte character array to hold incoming data from a pc/mac/other. byte O2_received_from_computer = 0; //we need to know how many characters have been received. byte O2_serial_event = false; //a flag to signal when data has been received from the pc/mac/other. byte O2_code = 0; //used to hold the I2C response code. char O2_data[20]; //we make a 20-byte character array to hold incoming data from the o2 sensor. byte O2_in_char = 0; //used as a 1 byte buffer to store inbound bytes from the o2 sensor. byte O2_i = 0; //counter used for o2_data array. //int O2_time_ = 600; //used to set the delay needed to process the command sent to the EZO o2 sensor. char *HUM; //char pointer used in string parsing. char *TMP; //char pointer used in string parsing. char *NUL; //char pointer used in string parsing (the sensor outputs some text that we don't need). char *DEW; //char pointer used in string parsing. char *O2_reading; char *O2_reading_2; float HUM_float; //float var used to hold the float value of the humidity. float TMP_float; //float var used to hold the float value of the temperatur. float DEW_float; //float var used to hold the float value of the dew point. float O2_float; float CO2Con_float; void setup() //hardware initialization. { Serial.begin(9600); //enable serial port. Wire.begin(); //enable I2C port. while(!Serial); //wait for serial monitor to be open } void serialEvent() { //this interrupt will trigger when the data coming from the serial monitor(pc/mac/other) is received. received_from_computer = Serial.readBytesUntil(13, computerdata, 22); //we read the data sent from the serial monitor(pc/mac/other) until we see a &lt;CR&gt;. We also count how many characters have been received. computerdata[received_from_computer] = 0; //stop the buffer from transmitting leftovers or garbage. serial_event = true; //set the serial event flag. } void loop() { //the main loop. if (serial_event == true) { //if a command was sent to the EZO device. for (i = 0; i &lt;= received_from_computer; i++) { //set all char to lower case, this is just so this exact sample code can recognize the &quot;sleep&quot; command. computerdata[i] = tolower(computerdata[i]); //&quot;Sleep&quot; ≠ &quot;sleep&quot; } i=0; //reset i, we will need it later //---------------------------------------------------------EZO-HUM Sensor-----------------------------------------------------------------------------// Wire.beginTransmission(HUM_address); //call the circuit by its ID number. Wire.write(computerdata); //transmit the command that was sent through the serial port. Wire.endTransmission(); //end the I2C data transmission. // Need to talk to each sensor separately. Because they're all Atlas Scientific EZO sensors, they all respond to the same commands if (strcmp(computerdata, &quot;sleep&quot;) != 0) { //if the command that has been sent is NOT the sleep command, wait the correct amount of time and request data. //if it is the sleep command, we do nothing. Issuing a sleep command and then requesting data will wake the Humidity sensor. delay(time_); //wait the correct amount of time for the circuit to complete its instruction. Wire.requestFrom(HUM_address, 22, 1); //call the circuit and request 22 bytes. code = Wire.read(); //the first byte is the response code, we read this separately. switch (code) { //switch case based on what the response code is. case 1: //decimal 1. Serial.println(&quot;HUM Success&quot;); //means the command was successful. break; //exits the switch case. case 2: //decimal 2. Serial.println(&quot;HUM Failed&quot;); //means the command has failed. break; //exits the switch case. case 254: //decimal 254. Serial.println(&quot;HUM Pending&quot;); //means the command has not yet been finished calculating. break; //exits the switch case. case 255: //decimal 255. Serial.println(&quot;HUM No Data&quot;); //means there is no further data to send. break; //exits the switch case. } while (Wire.available()) { //are there bytes to receive. in_char = Wire.read(); //receive a byte. Humidity_data[i] = in_char; //load this byte into our array. //Serial.println((int)in_char); i += 1; //incur the counter for the array element. if (in_char == 0) { //if we see that we have been sent a null command. i = 0; //reset the counter i to 0. break; //exit the while loop. } } if (computerdata[0] == 'r') string_pars(); //uncomment this function if you would like to break up the comma separated string into its individual parts. } //---------------------------------------------------------EZO-O2 Sensor-----------------------------------------------------------------------------// Wire.beginTransmission(O2_address); //call the circuit by its ID number. Wire.write(computerdata); //transmit the command that was sent through the serial port. Wire.endTransmission(); //end the I2C data transmission. if (strcmp(computerdata, &quot;sleep&quot;) != 0) { //if the command that has been sent is NOT the sleep command, wait the correct amount of time and request data. //if it is the sleep command, we do nothing. Issuing a sleep command and then requesting data will wake the Humidity sensor. delay(time_); //wait the correct amount of time for the circuit to complete its instruction. Wire.requestFrom(O2_address, 22, 1); //call the circuit and request 22 bytes. O2_code = Wire.read(); //the first byte is the response code, we read this separately. switch (O2_code) { //switch case based on what the response code is. case 1: //decimal 1. Serial.println(&quot;O2 Sensor Success&quot;); //means the command was successful. break; //exits the switch case. case 2: //decimal 2. Serial.println(&quot;O2 Sensor Failed&quot;); //means the command has failed. break; //exits the switch case. case 254: //decimal 254. Serial.println(&quot;O2 Sensor Pending&quot;); //means the command has not yet been finished calculating. break; //exits the switch case. case 255: //decimal 255. Serial.println(&quot;O2 Sensor No Data&quot;); //means there is no further data to send. break; //exits the switch case. } while (Wire.available()) { //are there bytes to receive. O2_in_char = Wire.read(); //receive a byte. O2_data[i] = O2_in_char; //load this byte into our array. Serial.println((int)O2_in_char); Serial.println(O2_data); i += 1; //incur the counter for the array element. if (O2_in_char == 0) { //if we see that we have been sent a null command. i = 0; //reset the counter i to 0. break; //exit the while loop. } } // Serial.print(&quot;O2 Concentration:&quot;); //This code doesn't output any information, although the program receives bytes which display in the while loop. // Serial.println(O2_data); // Serial.println(); if (computerdata[0] == 'r') O2_string_pars(); //This code also doesn't output any information. } //---------------------------------------------------------EZO-CO2 Sensor-----------------------------------------------------------------------------// Wire.beginTransmission(CO2_address); //call the circuit by its ID number. Wire.write(computerdata); //transmit the command that was sent through the serial port. Wire.endTransmission(); //end the I2C data transmission. if (strcmp(computerdata, &quot;sleep&quot;) != 0) { //if the command that has been sent is NOT the sleep command, wait the correct amount of time and request data. //if it is the sleep command, we do nothing. Issuing a sleep command and then requesting data will wake the Humidity sensor. delay(time_); //wait the correct amount of time for the circuit to complete its instruction. Wire.requestFrom(CO2_address, 22, 1); //call the circuit and request 22 bytes. CO2_code = Wire.read(); //the first byte is the response code, we read this separately. switch (CO2_code) { //switch case based on what the response code is. case 1: //decimal 1. Serial.println(&quot;CO2 Sensor Success&quot;); //means the command was successful. break; //exits the switch case. case 2: //decimal 2. Serial.println(&quot;CO2 Sensor Failed&quot;); //means the command has failed. break; //exits the switch case. case 254: //decimal 254. Serial.println(&quot;CO2 Sensor Pending&quot;); //means the command has not yet been finished calculating. break; //exits the switch case. case 255: //decimal 255. Serial.println(&quot;CO2 Sensor No Data&quot;); //means there is no further data to send. break; //exits the switch case. } while (Wire.available()) { //are there bytes to receive. CO2_in_char = Wire.read(); //receive a byte. CO2_data[i] = CO2_in_char; //load this byte into our array. //Serial.println((int)CO2_in_char); i += 1; //incur the counter for the array element. if (CO2_in_char == 0) { //if we see that we have been sent a null command. i = 0; //reset the counter i to 0. break; //exit the while loop. } } Serial.print(&quot;CO2 Concentration:&quot;); Serial.println(CO2_data); } serial_event = false; //reset the serial event flag // if (computerdata[0] == 'r') string_pars(); //uncomment this function if you would like to break up the comma separated string into its individual parts. } } void string_pars() { //this function will break up the CSV string into its 3 individual parts. HUM|TMP|DEW. //this is done using the C command “strtok”. HUM = strtok(Humidity_data, &quot;,&quot;); //let's pars the string at each comma. TMP = strtok(NULL, &quot;,&quot;); //let's pars the string at each comma. NUL = strtok(NULL, &quot;,&quot;); //let's pars the string at each comma (the sensor outputs the word &quot;DEW&quot; in the string, we dont need it. DEW = strtok(NULL, &quot;,&quot;); //let's pars the string at each comma. Serial.println(); //this just makes the output easier to read by adding an extra blank line. Serial.print(&quot;HUM:&quot;); //we now print each value we parsed separately. Serial.println(HUM); //this is the humidity value. Serial.print(&quot;Air TMP:&quot;); //we now print each value we parsed separately. Serial.println(TMP); //this is the air temperatur value. Serial.print(&quot;DEW:&quot;); //we now print each value we parsed separately. Serial.println(DEW); //this is the dew point. Serial.println(); //uncomment this section if you want to take the values and convert them into floating point number. /* HUM_float=atof(HUM); TMP_float=atof(TMP); DEW_float=atof(DEW); */ } void O2_string_pars() { //this function will break up the CSV string //this is done using the C command “strtok”. O2_reading = strtok(O2_data, &quot;,&quot;); //let's pars the string at each comma. // O2_reading_2 = strtok(NULL, &quot;,&quot;); Serial.println(); //this just makes the output easier to read by adding an extra blank line. Serial.print(&quot;O2 Concentration: &quot;); Serial.println(O2_reading); // Serial.println(&quot;O2 extra info: &quot;); // Serial.print(O2_reading_2); } </code></pre> <p>The following is the output from the program:</p> <blockquote> <p>HUM Success</p> <p>HUM:45.39</p> <p>Air TMP:23.61</p> <p>DEW:11.16</p> <p>O2 Sensor Success</p> <p>50</p> <p>48</p> <p>46</p> <p>56</p> <p>53</p> <p>0</p> <p>O2 Concentration:</p> <p>CO2 Sensor Success</p> <p>CO2 Concentration:599</p> </blockquote>
<p>You are relying on a NULL byte being received to reset your <code>i</code> pointer variable. If that NULL never arrives for whatever reason you won't be writing your new data to the start of your next array.</p> <p>You should <em>always</em> reset the counter before receiving new data regardless of what you have just received.</p>
89883
|char|
Assign a list of char *
2022-06-12T16:30:05.183
<p>Explain in a simple example. How to pass a <code>char*</code> to a function?</p> <pre><code>#define name1 &quot;ABCD&quot; #define name2 &quot;EFGH&quot; #define name3 &quot;HIJK&quot; char *list[3] = {}; void printList(char *l, int x) { for (int i = 0; i &lt; x; i++) { Serial.println(l[i]); } } void setup() { // put your setup code here, to run once: Serial.begin(115200); Serial.println(&quot;start&quot;); list[0] = name1; list[1] = name2; list[2] = name3; printList(list, 3); } void loop() { // put your main code here, to run repeatedly: } </code></pre> <p>I get an error:</p> <pre><code>/home/guy/Documents/Dropbox/Arduino/sketch_jun12a/sketch_jun12a.ino: In function 'void setup()': sketch_jun12a:24:13: error: cannot convert 'char**' to 'char*' 24 | printList(list, 3); | ^~~~ | | | char** /home/guy/Documents/Dropbox/Arduino/sketch_jun12a/sketch_jun12a.ino:7:22: note: initializing argument 1 of 'void printList(char*, int)' 7 | void printList(char *l, int x) { | ~~~~~~^ exit status 1 cannot convert 'char**' to 'char*' </code></pre>
<p>Just change this:</p> <pre class="lang-cpp prettyprint-override"><code>void printList(char *l, int x) { </code></pre> <p>to this:</p> <pre class="lang-cpp prettyprint-override"><code>void printList(char **l, int x) { </code></pre> <p>OK, this deserves some explanation...</p> <p>In C and C++, when you <strong>use</strong> (not when you <em>define</em>) an array identifier, it <a href="https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay">decays to a pointer to its first element</a>. In this case,</p> <pre class="lang-cpp prettyprint-override"><code>char *list[3] = {}; </code></pre> <p>is an array of pointers to <code>char</code>. When you use it here:</p> <pre class="lang-cpp prettyprint-override"><code>printList(list, 3); </code></pre> <p>it decays to a pointer to pointer to <code>char</code>. Thus the double <code>*</code> needed in the parameter declaration.</p> <p><strong>Side note</strong>: to get really correct C++, you should replace every instance of <code>char</code> by <code>const char</code>. This is because the characters in question belong to string literals, and you are not allowed to modify a string literal at run time.</p>
89888
|string|float|platformio|
Enable full float-capable snprintf() library with PlatformIO
2022-06-13T00:40:50.293
<p>I want to use snprintf() to format floats to a string.</p> <p>I know the &quot;normal&quot; version of Arduino's avrlibc had all the float-formatting code removed to make it smaller.</p> <p>I also know that at some point in the fairly recent past, it became possible to force gcc to use an alternate (forked?) larger Arduino avrlibc that had all the float-formatting functionality that was originally removed put back in.</p> <p>However... I'm still trying to find an actual explanation of <em>how to <strong>do</strong> that</em> for an Arduino project using <strong>PlatformIO</strong>.</p> <p>I found a clue someplace where someone said, &quot;change linker rules in platform.txt file to enable floating point xxprintf()&quot; (which hopefully enables floating point support in other float-to-string functions as well).</p> <p>Problem #1: <code>platform.txt</code> appears to be global rather than local to this one project. There's no file named &quot;platform.txt&quot; anywhere in the project's directory.</p> <p>Problem #2: I <strong>do</strong> have <em>several dozen</em> files on my computer named <code>platform.txt</code>... I don't know which one is the one that actually matters to PlatformIO, and I don't know enough about PlatformIO's internals to know how to figure out which <code>platform.txt</code> is the one that <em>matters</em>.</p> <p>Problem #3: Even if I manage to figure out which <code>platform.txt</code> is the one I need to modify, I still don't know what exact modifications actually need to be <em>made</em>.</p> <hr /> <p>Update: I stumbled over a thread in Arduino's Issue discussion (<a href="https://github.com/arduino/ArduinoCore-avr/issues/293" rel="nofollow noreferrer">&quot;Sprintf for floats on Arduino Mega 293&quot;</a>) that said to append the text quoted further down to boards.txt. The relevant line appears to be <code>mega.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt</code></p> <p>So... I'm guessing that what I need to put somewhere in <code>platform.txt</code> (once I figure out which <code>platform.txt</code> is the one that matters) is <code>-Wl,-u,vfprintf -lprintf_flt</code></p> <pre><code>############################################################## menu.printf=AVR printf Version menu.scanf=AVR scanf Version yun.menu.printf.default=Default printf yun.menu.printf.default.avr_printf_flags= yun.menu.printf.full=Full printf yun.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt yun.menu.printf.minimal=Minimal printf yun.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min yun.menu.scanf.default=Default scanf yun.menu.scanf.default.avr_scanf_flags= yun.menu.scanf.full=Full scanf yun.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt yun.menu.scanf.minimal=Minimal scanf yun.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min yun.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} uno.menu.printf.default=Default printf uno.menu.printf.default.avr_printf_flags= uno.menu.printf.full=Full printf uno.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt uno.menu.printf.minimal=Minimal printf uno.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min uno.menu.scanf.default=Default scanf uno.menu.scanf.default.avr_scanf_flags= uno.menu.scanf.full=Full scanf uno.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt uno.menu.scanf.minimal=Minimal scanf uno.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min uno.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} diecimila.menu.printf.default=Default printf diecimila.menu.printf.default.avr_printf_flags= diecimila.menu.printf.full=Full printf diecimila.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt diecimila.menu.printf.minimal=Minimal printf diecimila.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min diecimila.menu.scanf.default=Default scanf diecimila.menu.scanf.default.avr_scanf_flags= diecimila.menu.scanf.full=Full scanf diecimila.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt diecimila.menu.scanf.minimal=Minimal scanf diecimila.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min diecimila.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} nano.menu.printf.default=Default printf nano.menu.printf.default.avr_printf_flags= nano.menu.printf.full=Full printf nano.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt nano.menu.printf.minimal=Minimal printf nano.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min nano.menu.scanf.default=Default scanf nano.menu.scanf.default.avr_scanf_flags= nano.menu.scanf.full=Full scanf nano.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt nano.menu.scanf.minimal=Minimal scanf nano.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min nano.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} mega.menu.printf.default=Default printf mega.menu.printf.default.avr_printf_flags= mega.menu.printf.full=Full printf mega.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt mega.menu.printf.minimal=Minimal printf mega.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min mega.menu.scanf.default=Default scanf mega.menu.scanf.default.avr_scanf_flags= mega.menu.scanf.full=Full scanf mega.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt mega.menu.scanf.minimal=Minimal scanf mega.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min mega.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} megaADK.menu.printf.default=Default printf megaADK.menu.printf.default.avr_printf_flags= megaADK.menu.printf.full=Full printf megaADK.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt megaADK.menu.printf.minimal=Minimal printf megaADK.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min megaADK.menu.scanf.default=Default scanf megaADK.menu.scanf.default.avr_scanf_flags= megaADK.menu.scanf.full=Full scanf megaADK.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt megaADK.menu.scanf.minimal=Minimal scanf megaADK.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min megaADK.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} leonardo.menu.printf.default=Default printf leonardo.menu.printf.default.avr_printf_flags= leonardo.menu.printf.full=Full printf leonardo.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt leonardo.menu.printf.minimal=Minimal printf leonardo.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min leonardo.menu.scanf.default=Default scanf leonardo.menu.scanf.default.avr_scanf_flags= leonardo.menu.scanf.full=Full scanf leonardo.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt leonardo.menu.scanf.minimal=Minimal scanf leonardo.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min leonardo.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} micro.menu.printf.default=Default printf micro.menu.printf.default.avr_printf_flags= micro.menu.printf.full=Full printf micro.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt micro.menu.printf.minimal=Minimal printf micro.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min micro.menu.scanf.default=Default scanf micro.menu.scanf.default.avr_scanf_flags= micro.menu.scanf.full=Full scanf micro.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt micro.menu.scanf.minimal=Minimal scanf micro.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min micro.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} esplora.menu.printf.default=Default printf esplora.menu.printf.default.avr_printf_flags= esplora.menu.printf.full=Full printf esplora.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt esplora.menu.printf.minimal=Minimal printf esplora.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min esplora.menu.scanf.default=Default scanf esplora.menu.scanf.default.avr_scanf_flags= esplora.menu.scanf.full=Full scanf esplora.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt esplora.menu.scanf.minimal=Minimal scanf esplora.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min esplora.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} mini.menu.printf.default=Default printf mini.menu.printf.default.avr_printf_flags= mini.menu.printf.full=Full printf mini.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt mini.menu.printf.minimal=Minimal printf mini.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min mini.menu.scanf.default=Default scanf mini.menu.scanf.default.avr_scanf_flags= mini.menu.scanf.full=Full scanf mini.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt mini.menu.scanf.minimal=Minimal scanf mini.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min mini.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} ethernet.menu.printf.default=Default printf ethernet.menu.printf.default.avr_printf_flags= ethernet.menu.printf.full=Full printf ethernet.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt ethernet.menu.printf.minimal=Minimal printf ethernet.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min ethernet.menu.scanf.default=Default scanf ethernet.menu.scanf.default.avr_scanf_flags= ethernet.menu.scanf.full=Full scanf ethernet.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt ethernet.menu.scanf.minimal=Minimal scanf ethernet.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min ethernet.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} fio.menu.printf.default=Default printf fio.menu.printf.default.avr_printf_flags= fio.menu.printf.full=Full printf fio.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt fio.menu.printf.minimal=Minimal printf fio.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min fio.menu.scanf.default=Default scanf fio.menu.scanf.default.avr_scanf_flags= fio.menu.scanf.full=Full scanf fio.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt fio.menu.scanf.minimal=Minimal scanf fio.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min fio.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} bt.menu.printf.default=Default printf bt.menu.printf.default.avr_printf_flags= bt.menu.printf.full=Full printf bt.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt bt.menu.printf.minimal=Minimal printf bt.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min bt.menu.scanf.default=Default scanf bt.menu.scanf.default.avr_scanf_flags= bt.menu.scanf.full=Full scanf bt.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt bt.menu.scanf.minimal=Minimal scanf bt.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min bt.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} LilyPadUSB.menu.printf.default=Default printf LilyPadUSB.menu.printf.default.avr_printf_flags= LilyPadUSB.menu.printf.full=Full printf LilyPadUSB.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt LilyPadUSB.menu.printf.minimal=Minimal printf LilyPadUSB.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min LilyPadUSB.menu.scanf.default=Default scanf LilyPadUSB.menu.scanf.default.avr_scanf_flags= LilyPadUSB.menu.scanf.full=Full scanf LilyPadUSB.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt LilyPadUSB.menu.scanf.minimal=Minimal scanf LilyPadUSB.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min LilyPadUSB.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} lilypad.menu.printf.default=Default printf lilypad.menu.printf.default.avr_printf_flags= lilypad.menu.printf.full=Full printf lilypad.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt lilypad.menu.printf.minimal=Minimal printf lilypad.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min lilypad.menu.scanf.default=Default scanf lilypad.menu.scanf.default.avr_scanf_flags= lilypad.menu.scanf.full=Full scanf lilypad.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt lilypad.menu.scanf.minimal=Minimal scanf lilypad.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min lilypad.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} pro.menu.printf.default=Default printf pro.menu.printf.default.avr_printf_flags= pro.menu.printf.full=Full printf pro.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt pro.menu.printf.minimal=Minimal printf pro.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min pro.menu.scanf.default=Default scanf pro.menu.scanf.default.avr_scanf_flags= pro.menu.scanf.full=Full scanf pro.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt pro.menu.scanf.minimal=Minimal scanf pro.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min pro.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} atmegang.menu.printf.default=Default printf atmegang.menu.printf.default.avr_printf_flags= atmegang.menu.printf.full=Full printf atmegang.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt atmegang.menu.printf.minimal=Minimal printf atmegang.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min atmegang.menu.scanf.default=Default scanf atmegang.menu.scanf.default.avr_scanf_flags= atmegang.menu.scanf.full=Full scanf atmegang.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt atmegang.menu.scanf.minimal=Minimal scanf atmegang.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min atmegang.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} robotControl.menu.printf.default=Default printf robotControl.menu.printf.default.avr_printf_flags= robotControl.menu.printf.full=Full printf robotControl.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt robotControl.menu.printf.minimal=Minimal printf robotControl.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min robotControl.menu.scanf.default=Default scanf robotControl.menu.scanf.default.avr_scanf_flags= robotControl.menu.scanf.full=Full scanf robotControl.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt robotControl.menu.scanf.minimal=Minimal scanf robotControl.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min robotControl.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} robotMotor.menu.printf.default=Default printf robotMotor.menu.printf.default.avr_printf_flags= robotMotor.menu.printf.full=Full printf robotMotor.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt robotMotor.menu.printf.minimal=Minimal printf robotMotor.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min robotMotor.menu.scanf.default=Default scanf robotMotor.menu.scanf.default.avr_scanf_flags= robotMotor.menu.scanf.full=Full scanf robotMotor.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt robotMotor.menu.scanf.minimal=Minimal scanf robotMotor.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min robotMotor.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} gemma.menu.printf.default=Default printf gemma.menu.printf.default.avr_printf_flags= gemma.menu.printf.full=Full printf gemma.menu.printf.full.avr_printf_flags=-Wl,-u,vfprintf -lprintf_flt gemma.menu.printf.minimal=Minimal printf gemma.menu.printf.minimal.avr_printf_flags=-Wl,-u,vfprintf -lprintf_min gemma.menu.scanf.default=Default scanf gemma.menu.scanf.default.avr_scanf_flags= gemma.menu.scanf.full=Full scanf gemma.menu.scanf.full.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_flt gemma.menu.scanf.minimal=Minimal scanf gemma.menu.scanf.minimal.avr_scanf_flags=-Wl,-u,vfscanf -lscanf_min gemma.compiler.c.elf.extra_flags={avr_printf_flags} {avr_scanf_flags} ############################################################## </code></pre> <h3>Update 2:</h3> <p>I found what appears to be the solution &amp; posted it as my own answer, but I'm going to hold off for a day or two to test it thoroughly and make sure it actually works.</p>
<p>I finally found the answer at <a href="https://github.com/sstaub/LCDi2c" rel="nofollow noreferrer">https://github.com/sstaub/LCDi2c</a></p> <p>When using PlatformIO, add the following line to <code>platformio.ini</code> to enable full support for floats to printf():</p> <p><code>build_flags = -Wl,-u,vfprintf -lprintf_flt -lm</code></p> <h3>Caution:</h3> <p>This solution increases the amount of required flash by at least 2k. If you're using a Mega2560, you probably have flash to burn and really don't care. If you're using an Uno, Leonardo, Nano, or some other smaller AVR-based variant... it might matter, and you might <em>have</em> to care.</p> <p>Tip: if the Nano/Leonardo/Uno doesn't have enough flash or SRAM, but you don't have space for a full-blown Mega2560, consider the &quot;Arduino Nano Every&quot;. It uses the ATMega4809, with 48k flash and 6k SRAM.</p>
89890
|arduino-uno|arduino-mega|library|communication|calibration|
Fluctuation in 4 half bridge load cell via combinator
2022-06-13T09:25:09.883
<p>I'm currently using a Sparkfun 4 Half-Bridge load sensor (50 Kg) with combinator and amplifier both are from the Sparkfun. Link:<a href="https://www.sparkfun.com/products/10245" rel="nofollow noreferrer">https://www.sparkfun.com/products/10245</a> (For Load Sensors)<a href="https://www.sparkfun.com/products/13878" rel="nofollow noreferrer">https://www.sparkfun.com/products/13878</a> (Combinator) <a href="https://www.sparkfun.com/products/13879" rel="nofollow noreferrer">https://www.sparkfun.com/products/13879</a> (HX711) Our application requires long-term use i.e 8 to 10 hours of load application and monitoring the weight change during this time. Is this possible to achieve the above requirement using these chips/amplifiers? As we have experienced a drift in the readings if a weight is placed for more than approx. 3 minutes. We are using 4 half-bridge sensors, a combinator, and an amplifier.The issues I am tackling right now are,</p> <ol> <li>Zero balance: Load sensor value exponentially increases or decreases after calibration(this is a cyclic thing and keeps happening). The error ranges usually from -20g to +40g.</li> <li>Drift in reading: When the load is placed and kept for more than 3 minutes a drift is observed which increases with time and rises up to 50 to 60g. Can you please assist in this matter? have used different libraries. Results are the same.</li> </ol>
<p>Consider a change in temperature either the cause or partially the cause for weight drift. <a href="https://www.interfaceforce.com/understanding-load-cell-temperature-compensation/" rel="nofollow noreferrer">This supplier web page</a> talks about load cell temperature compensation. There they consider a 2000lb load cell. Their chart infers a 20 degree Fahrenheit change can cause an temperature uncompensated load cell to change about 1.5lb.</p> <p><a href="https://i.stack.imgur.com/5PuRH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5PuRH.jpg" alt="enter image description here" /></a></p>
89902
|c++|platformio|
How to do 'for' loop over inline anonymous array
2022-06-14T06:19:11.653
<p>I have a bunch of pins given names in the header:</p> <pre><code>#define DIP5 53 #define DIP4 52 #define DIP3 51 #define DIP2 50 #define DIP1 49 #define DIP0 48 </code></pre> <p>If it's not obvious, I have a bunch of DIP switches connected to digital pins 48..53 on an Arduino Mega2560</p> <p>In setup(), I need to set them all to INPUT_PULLUP. I know it would probably be less total effort to just do a series of pinMode commands, like:</p> <pre><code>pinMode(DIP5, INPUT_PULLUP); pinMode(DIP4, INPUT_PULLUP); // ... and so on </code></pre> <p>... but I'm trying to enrich my C++ skills &amp; be fancy, so I'm trying to figure out how to declare an anonymous array and foreach through it... something like:</p> <pre><code>for (int pin : {DIP5, DIP4, DIP3, DIP2, DIP1, DIP0}) { pinMode(pin, INPUT_PULLUP); } </code></pre> <p>... which, presumably, the compiler will optimize away into 6 inline pinMode commands anyway, but let me feel good about having pretty source code ;-)</p> <p>except... when I try it, I get the following error:</p> <p><code>error: deducing from brace-enclosed initializer list requires #include &lt;initializer_list&gt;</code></p> <p>... but when I add <code>#include &lt;initializer_list&gt;</code>, I get a different error:</p> <p><code>fatal error: initializer_list: No such file or directory</code></p> <p><strong>Any ideas what's wrong?</strong></p> <p>also... <em>can</em> I safely assume that the compiler will just unroll the whole thing behind the scenes, or is there a real risk it will <em>actually</em> declare a <em>real</em> array in SRAM just to iterate through one time?</p>
<p>Edgar Bonet <a href="https://arduino.stackexchange.com/a/89904/70020">answers</a> why <code>for (int pin : {DIP5, DIP4, DIP3, DIP2, DIP1, DIP0}) {</code> isn't working. What you would get (where supported) with this syntax is an <code>initializer_list</code> which itself is not an <em>array type</em>, although it is <em>backed</em> by an array.</p> <p>If you really did want to do something <em>like</em> that with an AVR-based Arduino you could do:</p> <pre class="lang-cpp prettyprint-override"><code>for (int pin : (const int []){DIP5, DIP4, DIP3, DIP2, DIP1, DIP0}) { pinMode(pin, INPUT_PULLUP); } </code></pre> <p>This is technically not standard C++. It is the use of something called a <a href="https://en.cppreference.com/w/c/language/compound_literal" rel="nofollow noreferrer">compound-literal</a>, which is being used to make an array typed value. This is a feature of C language feature (from C99 onward), not C++. However, the compiler and its configuration for Arduino allows its use as a language extension.</p> <p>Should you do this? <em>Perhaps</em> not, for the reasons that Edgar, 6v6gt, and jsotola point out. However, this much <em>can</em> be done if you really wanted. With respect to what it's doing efficiency-wise, you should test it.</p>
89912
|arduino-mega|softwareserial|imu|
Using Software Serial on Arduino Mega
2022-06-15T06:07:01.160
<p>So Im using this sensor: <a href="https://wiki.dfrobot.com/Serial_6_Axis_Accelerometer_SKU_SEN0386" rel="nofollow noreferrer">https://wiki.dfrobot.com/Serial_6_Axis_Accelerometer_SKU_SEN0386</a> with this library <a href="https://github.com/DFRobotdl/DFRobot_WT61PC" rel="nofollow noreferrer">https://github.com/DFRobotdl/DFRobot_WT61PC</a></p> <p>Im using 2 sensors but got poor frequency on Arduino Uno and decicded to switch to Mega since it supports multiple communications at once.</p> <p>This code works perfectly fine on Uno, but doesnt on Mega. Of course I tried using this method: <a href="https://docs.arduino.cc/built-in-examples/communication/MultiSerialMega" rel="nofollow noreferrer">https://docs.arduino.cc/built-in-examples/communication/MultiSerialMega</a> and I know I shouldnt be using Software Serial on Mega but <strong>this library has been written using Software Serial and I cant use a different method</strong> (or at least thats how I understand it).</p> <p>Here is the reason.</p> <pre class="lang-cpp prettyprint-override"><code>SoftwareSerial mySerial(10, 11); DFRobot_WT61PC sensor(&amp;mySerial); </code></pre> <p>So I tried multiple variations of pins (ones supporting UART, pcint, TX/RX) <a href="https://docs.arduino.cc/learn/built-in-libraries/software-serial" rel="nofollow noreferrer">https://docs.arduino.cc/learn/built-in-libraries/software-serial</a> and nothing seems to we working. Also tried removing the SD card reader, tried the original example code. I also tried Hardware Serial as it should be but again, it doesnt support this sensor and ends up resulting in errors(or vice versa). Nothing.</p> <p>Here is the working Uno code:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;DFRobot_WT61PC.h&gt; #include &lt;SoftwareSerial.h&gt; #include &lt;SPI.h&gt; #include &lt;SD.h&gt; #define FILE_BASE_NAME &quot;Pomiar&quot; #define VCC2 7 const uint8_t CS_PIN = 4; SoftwareSerial mySerial(2, 3); SoftwareSerial mySerial2(5, 6); DFRobot_WT61PC sensor(&amp;mySerial); DFRobot_WT61PC sensor2(&amp;mySerial2); File myFile; File file; const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1; char fileName[] = FILE_BASE_NAME &quot;00.txt&quot;; void setup() { pinMode(VCC2,OUTPUT); digitalWrite(VCC2,HIGH); //Use Serial as debugging serial port Serial.begin(9600); Serial.print(&quot;Initializing SD card...&quot;); if (!SD.begin(4)) { Serial.println(&quot;initialization failed!&quot;); while (1); } Serial.println(&quot;initialization done.&quot;); while (SD.exists(fileName)) { if (fileName[BASE_NAME_SIZE + 1] != '9') { fileName[BASE_NAME_SIZE + 1]++; } else if (fileName[BASE_NAME_SIZE] != '9') { fileName[BASE_NAME_SIZE + 1] = '0'; fileName[BASE_NAME_SIZE]++; } else { Serial.println(F(&quot;Can't create file name&quot;)); return; } } //Use software serial port mySerial as communication seiral port mySerial.begin(9600); mySerial2.begin(9600); //Revise the data output frequncy of sensor FREQUENCY_0_1HZ for 0.1Hz, FREQUENCY_0_5HZ for 0.5Hz, FREQUENCY_1HZ for 1Hz, FREQUENCY_2HZ for 2Hz, // FREQUENCY_5HZ for 5Hz, FREQUENCY_10HZ for 10Hz, FREQUENCY_20HZ for 20Hz, FREQUENCY_50HZ for 50Hz, // FREQUENCY_100HZ for 100Hz, FREQUENCY_125HZ for 125Hz, FREQUENCY_200HZ for 200Hz. sensor.modifyFrequency(FREQUENCY_10HZ); sensor2.modifyFrequency(FREQUENCY_10HZ); } void loop() { long timestamp = millis(); float acc1; float acc2 ; float acc3 ; float gyro1 ; float gyro2 ; float gyro3; float angle1; float angle2; float angle3; float acc12 ; float acc22 ; float acc32 ; float gyro12; float gyro22 ; float gyro32 ; float angle12 ; float angle22; float angle32; mySerial.listen(); if (sensor.available()) { acc1 = sensor.Acc.X; acc2 = sensor.Acc.Y; acc3 = sensor.Acc.Z; gyro1 = sensor.Gyro.X; gyro2 = sensor.Gyro.Y; gyro3 = sensor.Gyro.Z; angle1 = sensor.Angle.X; angle2 = sensor.Angle.Y; angle3 = sensor.Angle.Z; } mySerial2.listen(); if (sensor2.available()) { acc12 = sensor2.Acc.X; acc22 = sensor2.Acc.Y; acc32 = sensor2.Acc.Z; gyro12 = sensor2.Gyro.X; gyro22 = sensor2.Gyro.Y; gyro32 = sensor2.Gyro.Z; angle12 = sensor2.Angle.X; angle22 = sensor2.Angle.Y; angle32 = sensor2.Angle.Z; } myFile = SD.open(fileName, FILE_WRITE); if (myFile) { myFile.print(timestamp); myFile.print(&quot;|&quot;); myFile.print(acc1); myFile.print(&quot;|&quot;); myFile.print(acc2); myFile.print(&quot;|&quot;); myFile.print(acc3); myFile.print(&quot;|&quot;); myFile.print(gyro1); myFile.print(&quot;|&quot;); myFile.print(gyro2); myFile.print(&quot;|&quot;); myFile.print(gyro3); myFile.print(&quot;|&quot;); myFile.print(angle1); myFile.print(&quot;|&quot;); myFile.print(angle2); myFile.print(&quot;|&quot;); myFile.print(angle3); myFile.println(&quot;&quot;); myFile.print(timestamp); myFile.print(&quot;|&quot;); myFile.print(acc12); myFile.print(&quot;|&quot;); myFile.print(acc22); myFile.print(&quot;|&quot;); myFile.print(acc32); myFile.print(&quot;|&quot;); myFile.print(gyro12); myFile.print(&quot;|&quot;); myFile.print(gyro22); myFile.print(&quot;|&quot;); myFile.print(gyro32); myFile.print(&quot;|&quot;); myFile.print(angle12); myFile.print(&quot;|&quot;); myFile.print(angle22); myFile.print(&quot;|&quot;); myFile.print(angle32); myFile.println(&quot;&quot;); myFile.close(); } else { Serial.println(&quot;error opening test.txt&quot;); } } </code></pre> <p>I also found this question: <a href="https://arduino.stackexchange.com/questions/37333/arduino-mega-2560-softwareserial-not-working">Arduino Mega 2560 SoftwareSerial Not Working</a>. The guy has exact problem as I do but nooone found a solution to it. I also want to note that the manufacturer states that this library and sensor works fine on Mega. Really need your help.</p> <p>cheers</p> <p>@edit So I did some tests and the only code that actually shows something in monitor is:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;DFRobot_WT61PC.h&gt; DFRobot_WT61PC sensor(&amp;Serial); void setup() { //Use Serial as debugging serial port //Use software serial port mySerial as communication seiral port Serial.begin(9600); sensor.modifyFrequency(FREQUENCY_10HZ); } void loop() { if (sensor.available()) { Serial.print(&quot;Acc\t&quot;); Serial.print(sensor.Acc.X); Serial.print(&quot;\t&quot;); Serial.print(sensor.Acc.Y); Serial.print(&quot;\t&quot;); Serial.println(sensor.Acc.Z); //acceleration information of X,Y,Z Serial.print(&quot;Gyro\t&quot;); Serial.print(sensor.Gyro.X); Serial.print(&quot;\t&quot;); Serial.print(sensor.Gyro.Y); Serial.print(&quot;\t&quot;); Serial.println(sensor.Gyro.Z); //angular velocity information of X,Y,Z Serial.print(&quot;Angle\t&quot;); Serial.print(sensor.Angle.X); Serial.print(&quot;\t&quot;); Serial.print(sensor.Angle.Y); Serial.print(&quot;\t&quot;); Serial.println(sensor.Angle.Z); //angle information of X, Y, Z Serial.println(&quot; &quot;); } } </code></pre> <p><a href="https://i.stack.imgur.com/hBHw1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hBHw1.png" alt="monitor" /></a> But as you see the output is corrupted.</p>
<p>It's quick and dirty but you can make it Mega compatible by deleting the line <code>#include &lt;SoftwareSerial.h&gt;</code>, and replacing the lines</p> <pre><code>SoftwareSerial mySerial(2, 3); SoftwareSerial mySerial2(5, 6); </code></pre> <p>with</p> <pre><code>#define mySerial Serial1 #define mySerial Serial2 </code></pre> <p>replacing <code>Serial1</code> and <code>Serial2</code> with whichever of the Mega's serial ports you wish to use for mySerial and mySerial2, and connecting your DFRobot sensor signals to the correct pins for your chosen hardware serial ports.</p>
89917
|audio|sound|delay|wave|
Tone() function pauses between notes
2022-06-15T19:05:35.770
<p>I tried to experiment with the <code>tone()</code> function that comes with the arduino library.</p> <p>I played around with the standard code example located here: <a href="https://www.arduino.cc/en/Tutorial/BuiltInExamples/toneMelody" rel="nofollow noreferrer">https://www.arduino.cc/en/Tutorial/BuiltInExamples/toneMelody</a></p> <p>This is the code:</p> <pre><code>#include &quot;pitches.h&quot; int melody[] = { NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4 }; int noteDurations[] = { 4, 8, 8, 4, 4, 4, 4, 4 }; void setup() { for (int thisNote = 0; thisNote &lt; 8; thisNote++) { int noteDuration = 1000 / noteDurations[thisNote]; tone(8, melody[thisNote], noteDuration); // to distinguish the notes, set a minimum time between them. // the note's duration + 30% seems to work well: int pauseBetweenNotes = noteDuration * 1.30; delay(pauseBetweenNotes); // stop the tone playing: noTone(8); } } void loop() { // no need to repeat the melody. } </code></pre> <p>However, the problem is that there is always a pause between notes. In musical terms, this is called <code>staccato</code>. I want to be able to play short melodies where there are no delays between the notes, and one note progresses to the next naturally. By the way, this is called <code>legato</code> in music theory.</p> <p>Now, in this example, the delay between the notes sounds good because this &quot;music piece&quot; is supposed to be played this way. But in every other song that i experimented with, there were always some pauses between notes.</p> <p>This is what this song sounds like: <a href="https://soundcloud.com/nikowow-1/normal" rel="nofollow noreferrer">https://soundcloud.com/nikowow-1/normal</a></p> <p>Naturally, my mind went to the <code>delay(pauseBetweenNotes)</code> function. So i thought this is what causes the delay between the notes. So i set it up to <code>0.5</code>. This is what it sounds like: <a href="https://soundcloud.com/nikowow-1/05a" rel="nofollow noreferrer">https://soundcloud.com/nikowow-1/05a</a></p> <p>As you can hear, it just speeds up the whole song. The delay between the notes remain, but the whole song is sped up (in a higher tempo, so to speak).</p> <p>In order to better hear the delay between the notes, please take a listen at the song when i selected a value of <code>3</code> - causing a smaller tempo, so that the delay between the notes can be more easily audible: <a href="https://soundcloud.com/nikowow-1/3a-1" rel="nofollow noreferrer">https://soundcloud.com/nikowow-1/3a-1</a></p> <p>I want to create some melodies where there are no delays between the notes and i am stuck.</p> <p>EDIT: If you remove the delay line alltogether, the song is played so quickly that only a click sound is heard.</p>
<p>there is</p> <pre><code> // to distinguish the notes, set a minimum time between them. // the note's duration + 30% seems to work well: int pauseBetweenNotes = noteDuration * 1.30; delay(pauseBetweenNotes); </code></pre> <p>so the *1.30 creates the pause.</p> <p>if you change it to</p> <pre><code> int pauseBetweenNotes = noteDuration; </code></pre> <p>there will be no pause between notes.</p> <p>The tone length is specified with the last parameter of the tone() function (<code>noteDuration</code> here).</p>
89926
|accelerometer|gyroscope|magnetometer|
Quaternion values from Arduino 9-axis motion shield seem very wrong
2022-06-16T13:54:16.823
<p>I am currently usinga BNO055 sensor fitted on the Arduino Nine-axis motion shield to measure ocean wave heights and periods. To do this, I'd like to use the quaternions provided, however I have a slight issue. A quaternion should be &lt;cos(theta/2), X<em>sin(theta/2), Y</em>sin(theta/2), Z*sin(theta/2)&gt;, with X, Y and Z the coordinates of a unit vector and theta the angle of rotation around that vector. Therefore, I expect all three to be inferior to one.</p> <p>However, when I run a simple code to see the raw data, the W given by my sensor when on the table is 16 375, and X, Y and Z values are in the high hundreds range...</p> <p>This gives me a wave height of hundreds of thousands of kilometers :slightly_smiling_face:</p> <p>Does anyone know why this happens? Do I need to divide the quaternion by it's norm to get the correct result? Or maybe I am misunderstanding the use of a quaternion?</p> <p>Oh, and I have calibrated the sensor beforehand</p> <p>Thanks in advance for your help</p>
<p>I am not familiar with this sensor, so I am just guessing.</p> <p>The sensor is likely giving you <a href="https://en.wikipedia.org/wiki/Fixed-point_arithmetic" rel="nofollow noreferrer">fixed-point</a> numbers. Judging from the real part, there are most likely 14 bits right of the implicit radix point. If that is the case, the actual quaternion can be computed as:</p> <pre class="lang-c prettyprint-override"><code>float w = raw_w / 16384.0; float x = raw_x / 16384.0; float y = raw_y / 16384.0; float z = raw_z / 16384.0; </code></pre> <p>You can check whether this is reasonable by computing the norm, which should be very close to one.</p>
89933
|interrupt|bootloader|sleep|
External Interrupt not working on 3.3V atmega168
2022-06-17T03:24:44.617
<p>I made a 3.3V board and I've put both atmega328p (that I pulled off of a 3.3V pro mini), and an atmega168 that I bootloaded (using USBtinyISP whilst selecting board &quot;Arduino Pro or Pro Mini&quot; and &quot;atmega168 (3.3V, 8MHz&quot;) .</p> <p>Everything works perfectly with the atmega328 - code works and interrupts do as well - which function to pull the Arduino out of sleep when INT0 rises.</p> <p>However on the Atmega168, the interrupt doesn't seem to work. All the normal code works as expected (communications, instructions etc), just not the interrupt. After the Arduino goes to sleep, I can't wake it since the interrupt isn't working.</p> <p>Basic code below:</p> <pre><code>#include &lt;avr/sleep.h&gt;//this AVR library contains the methods that controls the sleep modes byte interruptPin = 2; //Turn board on/off unsigned long shutDownTimer = 0; // Timer for shutdown void setup() { Serial.begin(57600); pinMode(interruptPin, INPUT); //Set pin d2 to input using the buildin pullup resistor Serial.println(&quot;Starting&quot;); } void loop() { Serial.println(&quot;Awake&quot;); delay(1000); // Shutdown control if (digitalRead(interruptPin) == LOW ) { Serial.println(&quot;Shutdown detected&quot;); shutDownTimer = millis(); while (digitalRead(interruptPin) == LOW ) { if (millis() - shutDownTimer &gt; 1000) { Serial.println(&quot;sleep mode triggered&quot;); Going_To_Sleep(); } } } } void Going_To_Sleep() { sleep_enable();//Enabling sleep mode delay(1000); set_sleep_mode(SLEEP_MODE_PWR_DOWN);//Setting the sleep mode, in our case full sleep delay(1000); //wait a second to allow the led to be turned off before going to sleep attachInterrupt(0, wakeUp, RISING);//attaching a interrupt to pin d2 Serial.println(&quot;Interrrupt attached&quot;);//Print message to serial monitor sleep_cpu();//activating sleep mode Serial.println(&quot;just woke up!&quot;);//next line of code executed after the interrupt } void wakeUp() { sleep_disable();//Disable sleep mode detachInterrupt(0); //Removes the interrupt from pin 2; Serial.println(&quot;Interrrupt Fired - wakeup&quot;);//Print message to serial monitor } </code></pre> <p>Instead of using &quot;attachInterrupt(0, wakeUp, RISING);&quot; Ive also tried the following which also don't work:</p> <pre><code>attachInterrupt(INT0, wakeUp, RISING); attachInterrupt(digitalPinToInterrupt(interruptPin), wakeUp, RISING); attachInterrupt(32, wakeUp, RISING); //since its the pin of the chip? Hail Mary attachInterrupt(2, wakeUp, RISING); //obviously this won't work, Hail Mary 2 </code></pre> <p>I have no idea why the interrupts aren't working. I have an inkling it might be due to something fuse related within the boot loader, but I don't really understand things at that level (Though I'm happy to dive in with some guidance). Any guidance will be appreciated!</p>
<p>Depending on what signal you are using to wake the Arduino, you may also find pin change interrupts an alternative to the edge triggered interrupts you are currently using. These are usually more predictable in behaviour and less subject to nuanced interpretations of the data sheets. See <a href="https://playground.arduino.cc/Main/PinChangeInterrupt/" rel="nofollow noreferrer">https://playground.arduino.cc/Main/PinChangeInterrupt/</a> for examples of how to use these.</p>
89941
|buzzer|seeeduino-xiao|
passive buzzer is drawing 500mA
2022-06-17T13:03:08.450
<p>I am having a ridiculously hard time trying to make a passive buzzer work correctly on my Seeeduino XIAO.</p> <p>Here is the buzzer module : <a href="https://i.stack.imgur.com/KTWnE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KTWnE.png" alt="enter image description here" /></a></p> <p>Here is how I believe it works, assuming the SOT23 smd is a PNP transistor? : <a href="https://i.stack.imgur.com/ZFGoT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZFGoT.png" alt="enter image description here" /></a></p> <p>I plugged VCC to a +5V rail, GND to the ground rail, and I/O pin to my Seeeduino XIAO's pin 2 (aka &quot;A2 / D2&quot; : <a href="https://i.stack.imgur.com/yf5Fj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yf5Fj.jpg" alt="enter image description here" /></a></p> <p>When I write <code>DigitalWrite(2, LOW)</code>, I can mesure about 0.4V on pin 2, while <code>DigitalWrite(2, HIGH)</code> reads about 3.3V (I assume the 5V rail feeding my Seeeduino XIAO's VCC gets converted to 3v3 through an internal regulator)</p> <p>I understand I have to oscillate the signal to make this module buzz (remember it is a passive buzzer, or a transducer, whatever it is called), or simply use the <code>tone()</code> method, and I eventually managed to make this beep on and off every 1 second successfully during 10 seconds, but what bothers me is that I can NOT turn this module OFF after 10 seconds as a test in my sketch. It stops beeping after 10 sec as expected (<code>ìf (millis() &lt; 10000) { doBeep(); }</code> , but it still draws massive current and gets hot after that delay. It's like the PNP transistor never turns off? I tried both digitalWrite HIGH and LOW but no success.</p> <p>This is driving me crazy. What am I doing wrong?</p>
<p>You're right that it's a PNP transistor - the SS8550 to be precise.</p> <p>And therein lies the problem.</p> <p>When running at 5V to &quot;make no current flow&quot; through the base the voltage at the base has to be higher than 4.4V (5v - 0.6v), and since you're controlling it from a 3.3V microcontroller that can never happen. So you are right in thinking it never turns off - it never does.</p> <p>Even when you're &quot;beeping&quot; it it's not turning fully off, so the beep sounds you make will be reduced accordingly.</p> <p>You should power the board from 3.3V instead of 5V so the PNP can turn off fully. If that is not possible then switching the GPIO pin to INPUT mode will prevent it from driving the PNP thus allowing it to turn itself off.</p>
89960
|esp8266|pwm|
PWM on Wemos D1 Mini (esp8266 chip) does not work
2022-06-20T15:46:13.090
<p>I am working on a hobby project: creating an rc-(radio controlled)-toy car.</p> <p>I'm working with a <strong>Wemos D1 Mini</strong> (esp8266) microcontroller, <strong>L298N</strong> H-bridge (for controlling the motor) and I'm using the <strong>Arduino IDE</strong> to program it all.</p> <p>The project is quite simple: make the car drive around via an virtual joystick on an app. The project is quite fun and a nice learning experience for me. The project is going pretty well until this point.</p> <p>I can move the car forwards and backwards with a constant speed, but I'm not able to change the speed via a <strong>PWM</strong> signal. Actually, I'm not even sure if it is even possible to create a PWM signal on the Wemos D1 Mini, I have never done it before on this specific controller. I'm not an electrical engineer, so I'm not really familiar with very specific details about the controller itself.</p> <p>Can somebody help me create a PWM signal to control the speed of the car?</p> <p>This is what I have got now, very basic stuff:</p> <pre class="lang-c prettyprint-override"><code>void setup() { pinMode(D2, OUTPUT); pinMode(D5, OUTPUT); pinMode(D6, OUTPUT); pinMode(D7, OUTPUT); pinMode(D8, OUTPUT); } void forward() { digitalWrite(D5, LOW); digitalWrite(D6, HIGH); } void backward() { digitalWrite(D5, HIGH); digitalWrite(D6, LOW); } void setVelocity(int value){ analogWrite(D2, value); } void loop() { setVelocity(1023); forward(); } </code></pre> <p>Thanks in advance!</p> <p>Sincerly,</p> <p>Stefan</p>
<p>At one point <code>analogWrite</code> as it was implemented in the esp8266-core had defaulted to a 10-bit range. This is <a href="https://arduino-esp8266.readthedocs.io/en/latest/reference.html#analog-output" rel="nofollow noreferrer">no longer the case</a>. It defaults to 8-bit range now.</p> <p>In any case <code>analogWrite</code> is implemented to <a href="https://github.com/esp8266/Arduino/blob/f2d83ba/cores/esp8266/core_esp8266_wiring_pwm.cpp#L57,L59" rel="nofollow noreferrer">clamp</a> the given value to be within the range.</p> <p>If you were not experimenting in the bottom quarter of the velocity range with your code as written then you would have seen full velocity.</p> <p>You can change to working with the 8-bit range or use <code>analogWriteRange(new_range)</code> or <code>analogWriteResolution(bits)</code> as <a href="https://arduino-esp8266.readthedocs.io/en/latest/reference.html#analog-output" rel="nofollow noreferrer">this</a> mentions.</p> <p>Your code as is will produce a 50% duty cycle 1Khz signal on D2 if setVelocity is given 128 with the current core.</p>
89961
|arduino-uno|timers|isr|
ISR for very fast processes, strange code found. Has ISR effect on timer behaviour?
2022-06-20T15:50:11.340
<p>I found the following code within an example for performing very fast changes on a PWM-output. It works, however I'm wondering about some details.</p> <p>TIMER2 was set up in setup() as follows:</p> <pre><code>TCCR2A = 0; // We need no options in control register A TCCR2B = (1 &lt;&lt; CS21); // Set prescaller to divide by 8 TIMSK2 = (1 &lt;&lt; OCIE2A); // Set timer to call ISR when TCNT2 = OCRA2 OCR2A = 32; // sets the frequency of the generated wave sei(); // Enable interrupts to generate waveform! </code></pre> <p>If I understand that correctly, the timer will run until overflow and generate interrupts any time in between as defined by OCR2A.</p> <pre><code>ISR(TIMER2_COMPA_vect) { // Called each time TCNT2 == OCR2A static byte index=0; // Points to successive entries in the wavetable OCR1AL = wave[index++]; // Update the PWM output asm(&quot;NOP;NOP&quot;); // Fine tuning TCNT2 = 6; // Timing to compensate for time spent in ISR } </code></pre> <p>TIMER2 is used to call this routine in equidistant points in time. To adapt the timespan between two calls of the ISR the author sets OCR2A and within the ISR resets TCNT2. As the timer is reset at the end of the ISR there's some time &quot;already gone&quot; written into the start value of the timer. However there are two things I don't understand.</p> <ol> <li><p>Why isn't CTC mode used by setting WGM21 in TCCR2A? This should call the ISR in precise intervals.</p> </li> <li><p>If not using CTC mode the counter has to be reset by the ISR. But why isn't that done directly at the beginning of the ISR? Everytime the ISR gets some minor changes the correction value written into TCNT2 has to be changed.</p> </li> </ol> <p>Am I missing some vital detail? Or is my idea of using CTC better?</p> <p>For sake of completeness, the only other things done in setup() are configurations on timer1:</p> <pre><code>pinMode(9, OUTPUT); // Make timer's PWM pin an output TCCR1B = (1 &lt;&lt; CS10); // Set prescaler to full 16MHz TCCR1A |= (1 &lt;&lt; COM1A1); // PWM pin to go low when TCNT1=OCR1A TCCR1A |= (1 &lt;&lt; WGM10); // Put timer into 8-bit fast PWM mode TCCR1B |= (1 &lt;&lt; WGM12); </code></pre> <p>loop() is empty.</p>
<blockquote> <p>Why isn't CTC mode used by setting WGM21 in TCCR2A?</p> </blockquote> <p>As we cannot read the author's mind, we cannot say for sure. That being said, to me, the most likely reason is that either the author was not aware of CTC mode, or they just didn't think about it.</p> <p>You are right that CTC is the most straightforward way to get precise intervals. You are also right that the resetting the timer at the end of the ISR makes the code somewhat fragile. If, for some reason, I needed to avoid CTC in a code like this, I would</p> <pre class="lang-cpp prettyprint-override"><code>OCR2A += 32; </code></pre> <p>rather than resetting <code>TCNT2</code>.</p>
89968
|esp8266|json|
Determining ArduinoJSON document size based on file size
2022-06-21T11:09:14.727
<p>I'm trying to effectively allocate a doc's size, based on the size of the file saved in flash of ESP8266. Is there a way?</p> <p>For example: <code>file.size()</code> X 1.5</p>
<p>There is unfortunately no way to predict the size of the <a href="https://arduinojson.org/v6/api/jsondocument/" rel="nofollow noreferrer"><code>JsonDocument</code></a> from the file size alone.</p> <p>As a workaround, I suggest that you allocate a very large memory pool and shrink it after deserialization; like so:</p> <pre class="lang-cpp prettyprint-override"><code>DynamicJsonDocument doc(ESP.getMaxAllocHeap()); deserializeJson(doc, file); doc.shrinkToFit(); </code></pre> <p>Indeed, this program consumes more memory than strictly required, but only for a fraction of a second.</p> <p>See also:</p> <ul> <li><a href="https://arduinojson.org/v6/how-to/determine-the-capacity-of-the-jsondocument/" rel="nofollow noreferrer">How to determine the capacity of the JsonDocument?</a></li> <li><a href="https://arduinojson.org/v6/api/basicjsondocument/shrinktofit/" rel="nofollow noreferrer">BasicJsonDocument::shrinkToFit()</a></li> </ul>
89975
|arduino-mega|usb|spi|shields|
Funduino USB Host Shield problems
2022-06-22T08:14:06.070
<p>I'm currently working on connecting a Funduino version of usb host shield onto an arduino mega board. But the serial output shows &quot;osc did not start&quot;, which means the board can't find the shield. However the reset button works, so I estimate insufficient power being supplied.</p> <p><a href="https://i.stack.imgur.com/2KNVC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2KNVC.jpg" alt="enter image description here" /></a></p> <p>I'm aware of the bridging solution for the regular arduino module for the 3.3v and 5v (<a href="http://esp8266-notes.blogspot.com/2017/08/defective-arduino-usb-host-shield-boards.html" rel="nofollow noreferrer">example</a>). But how can this solution be applied to the Funduino model.</p> <p>Update: I've changed the SPI lines on the shield to the 6 ISCP pins on the Mega, but still no change in results.</p> <p>I performed a second test using board_qc, which returned:</p> <p>Circuits At Home 2011</p> <p>USB Host Shield Quality Control Routine</p> <p>Reading REVISION register... Die revision invalid. Value returned: 00</p> <p>Unrecoverable error - test halted!!</p> <p>0x55 pattern is transmitted via SPI</p> <p>Press RESET to restart test</p>
<p>That shield communicates over SPI. However the SPI pins it uses are the &quot;old&quot; style (10-13) for the Arduino UNO.</p> <p>The Mega doesn't use those pins, which is why the &quot;new&quot; style 6-pin SPI/ICSP header was added to boards.</p> <p>You will have to manually jumper the right pins to the SPI pins of the Mega using wires.</p>
89978
|atmega328|attiny|atmel|atmega16u2|atmega|
Can we use more than one timer when programming an Atmega32/16?
2022-06-22T12:18:57.870
<p>I tried to do a simple program using the ATmega16 microcontroller, the program is to toggle two LEDs the first one by using timer0 interrupt and the other using timer2 interrupt.</p>
<p>Yes, you can. However there is one thing to note:</p> <p><strong>Only one ISR can run at once.</strong></p> <p>That means that if one LED wants to toggle while the other one is in the process of toggling it will have to wait until that first ISR is finished before it can toggle.</p> <p>For simple LED toggling that won't be noticeable, but it's something you need to bear in mind if you are doing multiple things that require precise timing.</p>
89980
|esp8266|c|tcpip|
ESP8266 Wemos D1 min pro - how to change TCP_SND_BUF?
2022-06-22T12:47:56.480
<p>Is there any way to change the TCP send buffer size (TCP_SND_BUF) on this module ?</p> <p>Now it is equal to <code>TCP_SND_BUF = 2 * TCP_MSS = 2 * 1460 = 2920</code>.</p> <p>Editing <code>lwipopts.h</code> doesn't make any difference.</p> <p>The same question applies to <code>ΤCP_MSS</code>, <code>TCP_WND</code> etc.</p> <p>I am using v2 Higher Bandwidth variant. Platform is Microchip Studio with vMicro Arduino addon.</p>
<p>I finally figured it out the hard way :</p> <p><a href="https://github.com/esp8266/Arduino/discussions/8616" rel="nofollow noreferrer">https://github.com/esp8266/Arduino/discussions/8616</a></p> <hr /> <p>Install <strong>Git</strong> for windows (<a href="https://git-scm.com/download/win" rel="nofollow noreferrer">https://git-scm.com/download/win</a>)</p> <p>Install <strong>MinGW</strong> for windows (<a href="https://sourceforge.net/projects/mingw" rel="nofollow noreferrer">https://sourceforge.net/projects/mingw</a>)</p> <p>In <strong>MinGW</strong> installation manager, enable:</p> <ul> <li>mingw-developer-toolkit</li> <li>mingw32-base</li> <li>mingw32-gcc-g++</li> <li>msys-base</li> </ul> <p><em>(not sure if all are necessary but just in case)</em></p> <p>put <em>C:\MinGW\bin</em> in Windows PATH (check this <a href="https://www.rapidee.com" rel="nofollow noreferrer">https://www.rapidee.com</a>)</p> <h2><strong>reboot PC</strong></h2> <p>rename <strong>C:\MinGW\bin\mingw32-make.exe</strong> to <strong>C:\MinGW\bin\make.exe</strong></p> <p>open <strong>bash</strong> terminal (just type bash in run)</p> <p><em>(from now on assume that hardware files are in \Documents\Arduino\hardware\esp8266com\esp8266)</em></p> <p>go to <em>\tools\sdk\lwip2</em></p> <p>optional: change <strong>lwip options</strong> in <em>\tools\sdk\lwip2\builder\glue-lwip\arduino\lwipopts.h</em></p> <p>(caution : <strong>NOT</strong> <em>\tools\sdk\lwip2\include\lwipopts.h</em>, this will be overwritten !)</p> <p>type in bash: <strong>make install</strong> to build libraries in <em>\esp8266com\esp8266\tools\sdk\lwip2\builder</em></p> <p>type in bash: <strong>make clean</strong> to clean <em>\esp8266com\esp8266\tools\sdk\lwip2\builder</em></p> <p>finally copy new libraries to <em>\esp8266com\esp8266\tools\sdk\lib</em></p>
89986
|c++|
Create member object using constructor arguments, or pass reference to object via constructor
2022-06-23T04:33:58.443
<p>I'm not entirely sure about the proper C++ terminology, so I'll just illustrate what I'm trying to achieve by giving a Java example since it should be pretty obvious:</p> <pre><code>public class LcdDecorator { private HD44780Lcd lcd; public LcdDecorator(int rows, int cols, int i2cAddress) { this.lcd = new HD44780Lcd(rows, cols, i2cAddress); } } </code></pre> <p>or... alternatively...</p> <pre><code>public class LcdDecorator { private HD44780Lcd lcd; public LcdDecorator(HD44780Lcd lcd) { this.lcd = lcd; } } </code></pre> <p>For what it's worth, there's no real concern about scope... LcdDecorator is a Singleton that gets created in setup(), then lives forever and gets used by loop() until the power gets shut off.</p> <h4>Here's what I've attempted so far:</h4> <p><code>LcdFacade.h</code>:</p> <pre><code>#ifndef CORECONTROLLER_LCDFACADE_H #define CORECONTROLLER_LCDACADE_H #include &lt;stdint.h&gt; #include &quot;../.pio/libdeps/megaatmega2560/HD44780_LCD_PCF8574/src/HD44780_LCD_PCF8574.h&quot; class LcdFacade { public: LcdFacade(uint8_t rows, uint8_t cols, uint8_t i2cAddress) ; }; #endif //CORECONTROLLER_LCDFACADE_H </code></pre> <p><code>LcdFacade.cpp</code>:</p> <pre><code>#include &quot;LcdFacade.h&quot; #include &quot;../.pio/libdeps/megaatmega2560/HD44780_LCD_PCF8574/src/HD44780_LCD_PCF8574.h&quot; HD44780LCD lcd; LcdFacade::LcdFacade (uint8_t rows, uint8_t cols, uint8_t i2cAddress) : lcd{rows, cols, i2cAddress} { // ... the rest of the constructor goes here ... } </code></pre> <p>note: I also tried using parentheses instead of braces for lcd's constructor:</p> <pre><code>LcdFacade::LcdFacade(uint8_t rows, uint8_t cols, uint8_t i2cAddress) : lcd(rows, cols, i2cAddress) { </code></pre> <p>In CLion, the 'lcd{rows, cols, i2caddress}' portion of the constructor in LcdFacade.cpp is red-underlined, and reports <code>member initializer 'lcd' does not name a non-static data member or base class</code></p> <p>Meanwhile, gcc(?) reports <code>error: no matching function for call to 'HD44780LCD::HD44780LCD()</code> on line 4 of LcdFacade.cpp.</p> <p>Any ideas?</p>
<p>When you define</p> <pre class="lang-cpp prettyprint-override"><code>HD44780LCD lcd; </code></pre> <p>at global scope, you are creating a global variable that is initialized before <code>main()</code> is called. In this case, it is initialized with the default constructor <code>HD44780LCD::HD44780LCD()</code>, which does not exist, hence the error. You could avoid this error by calling a suitable constructor in the initialization, e.g.</p> <pre class="lang-cpp prettyprint-override"><code>HD44780LCD lcd(4, 20, 0x23); </code></pre> <p>but this may be inconvenient to you.</p> <p>If you want to initialize <code>lcd</code> in the constructor of <code>LcdFacade</code>, then it must be a non-static member of the class:</p> <pre class="lang-cpp prettyprint-override"><code>// In LcdFacade.h: class LcdFacade { public: LcdFacade(uint8_t rows, uint8_t cols, uint8_t i2cAddress); private: HD44780LCD lcd; // &lt;- non-static member }; // In LcdFacade.cpp: LcdFacade::LcdFacade(uint8_t rows, uint8_t cols, uint8_t i2cAddress) : lcd(rows, cols, i2cAddress) { ... } </code></pre>
89987
|web-server|float|data|
Why does the data I send to the server get rounded off and how do I send the entire float instead?
2022-06-23T07:10:57.603
<pre><code>#include &lt;Arduino.h&gt; #include &lt;WiFi.h&gt; #include &quot;WiFiManager.H&quot; #include &lt;HTTPClient.H&gt; #include &quot;ESPAsyncWebServer.h&quot; #include &lt;AsyncTCP.h&gt; float version = 1.9; uint32_t chipId = 0; String chipId2 = &quot;&quot;; int i; String serverName = &quot;http://d&quot;; // WiFiManager // Local intialization. Once its business is done, there is no need to keep it around WiFiManager wifiManager; // Create AsyncWebServer object on port 80 AsyncWebServer server2(80); WiFiServer server(80); // variables to count the pulses of the meters. int count1=0; float prior_count1=0; int count2=0; float prior_count2=0; int count3=0; float prior_count3=0; int count4=0; float prior_count4=0; int countgas=0; float prior_countgas=0; int countwater=0; float prior_countwater=0; String payloadpulse = &quot;0&quot;; unsigned long lastTime = 0; unsigned long timerDelay = 6000; String guifactor1 = &quot;1000&quot;; String guifactor2 = &quot;1000&quot;; String guifactor3 = &quot;1000&quot;; String guifactor4 = &quot;1000&quot;; String guifactorgas = &quot;1000&quot;; String guifactorwater = &quot;1000&quot;; String counter1 = &quot;1&quot;; String counter2 = &quot;1&quot;; String counter3 = &quot;1&quot;; String counter4 = &quot;1&quot;; String counter5 = &quot;1&quot;; String counter6 = &quot;1&quot;; // function to increment the meters value by 1. void pulse1() { if (counter1.toInt() == 1) { count1 = count1 + 1; } if (counter1.toInt() == 2) { count1 = count1 - 1; } } void pulse2() { if (counter2.toInt() == 1) { count2 = count2 + 1; } if (counter2.toInt() == 2) { count2 = count2 - 1; } } void pulse3() { if (counter3.toInt() == 1) { count3 = count3 + 1; } if (counter3.toInt() == 2) { count3 = count3 - 1; } } void pulse4() { if (counter4.toInt() == 1) { count4 = count4 + 1; } if (counter4.toInt() == 2) { count4 = count4 - 1; } } void pulsegas() { if (counter5.toInt() == 1) { countgas = countgas + 1; } if (counter5.toInt() == 2) { countgas = countgas - 1; } } void pulsewater() { if (counter6.toInt() == 1) { countwater = countwater + 1; } if (counter6.toInt() == 2) { countwater = countwater - 1; } } void setup() { Serial.begin(115200); wifiManager.autoConnect(&quot;ss&quot;, &quot;ss&quot;); pinMode(25, INPUT_PULLDOWN); // Set GPIO25 as digital output pin attachInterrupt(digitalPinToInterrupt(25), pulse1, RISING); pinMode(19, INPUT_PULLDOWN); // Set GPIO19 as digital output pin attachInterrupt(digitalPinToInterrupt(19), pulse2, RISING); pinMode(23, INPUT_PULLDOWN); // Set GPIO22 as digital output pin attachInterrupt(digitalPinToInterrupt(23), pulse3, RISING); pinMode(18, INPUT_PULLDOWN);// Set GPIO18 as digital output pin attachInterrupt(digitalPinToInterrupt(18), pulse4, RISING); pinMode(21, INPUT_PULLDOWN); // Set GPIO22 as digital output pin attachInterrupt(digitalPinToInterrupt(21), pulsegas, RISING); pinMode(5, INPUT_PULLDOWN); // Set GPIO5 as digital output pin attachInterrupt(digitalPinToInterrupt(5), pulsewater, RISING); } //-------------------------------------------------------------------- void loop() { float new_count1 = static_cast&lt;float&gt; (count1) / guifactor1.toInt(); float new_count2 = static_cast&lt;float&gt; (count2) / guifactor2.toInt(); float new_count3 = static_cast&lt;float&gt; (count3) / guifactor3.toInt(); float new_count4 = static_cast&lt;float&gt; (count4) / guifactor4.toInt(); float new_countgas = static_cast&lt;float&gt; (countgas) / guifactorgas.toInt(); float new_countwater = static_cast&lt;float&gt; (countwater) / guifactorwater.toInt(); // keeps track of the amount of pulses of pulse meters if (new_count1 != prior_count1 || new_count2 != prior_count2 || new_count3 != prior_count3 || new_count4 != prior_count4 || new_countgas != prior_countgas || new_countwater != prior_countwater) { Serial.println(new_count1, 4); Serial.println(new_count2, 4); Serial.println(new_count3, 4); Serial.println(new_count4, 4); Serial.println(new_countgas, 4); Serial.println(new_countwater, 4); prior_count1 = new_count1; prior_count2 = new_count2; prior_count3 = new_count3; prior_count4 = new_count4; prior_countgas = new_countgas; prior_countwater = new_countwater; } // sends an update to the web if ((new_count1 &gt; 0 &amp;&amp; ((millis() - lastTime) &gt; timerDelay)) || (new_count2 &gt; 0 &amp;&amp; ((millis() - lastTime) &gt; timerDelay)) || (new_count3 &gt; 0 &amp;&amp; ((millis() - lastTime) &gt; timerDelay)) || (new_count4 &gt; 0 &amp;&amp; ((millis() - lastTime) &gt; timerDelay)) || (new_countgas &gt; 0 &amp;&amp; ((millis() - lastTime) &gt; timerDelay)) || (new_countwater &gt; 0 &amp;&amp; ((millis() - lastTime) &gt; timerDelay))) { { // checks if wifi is connected. if (WiFi.status()== WL_CONNECTED) { HTTPClient http; // preparation HTTP GET request. String serverPath = serverName + &quot;?chip_id=&quot; + chipId + &quot;&amp;count1=&quot; + new_count1 + &quot;&amp;count2=&quot; + new_count2 + &quot;&amp;count3=&quot; + new_count3 + &quot;&amp;count4=&quot; + new_count4 + &quot;&amp;countgas=&quot; + new_countgas + &quot;&amp;countwater=&quot; + new_countwater; // Your Domain name with URL path or IP address with path. http.begin(serverPath.c_str()); // Send HTTP GET request. int httpResponseCode = http.GET(); // confirms the arrival of a response from the server or sends an error. if (httpResponseCode&gt;0) { count1 = 0; count2 = 0; count3 = 0; count4 = 0; countgas = 0; countwater = 0; payloadpulse = http.getString(); Serial.println(payloadpulse); } else { Serial.print(&quot;Error code: &quot;); Serial.println(httpResponseCode); } // closes the HTTP connection. http.end(); } else { Serial.println(&quot;WiFi Disconnected&quot;); } } } //reset timer when done sending data if (((millis() - lastTime) &gt; timerDelay)) { lastTime = millis(); } } </code></pre> <p>The program is a pulse counter which should add 0.001 pulse everytime it detects one. I expect it to send 0.006 to the server, but instead it sends 0.01. How do I make sure it doesn't send rounded data?</p>
<p>The constructor for the String object from float is this:</p> <pre><code>String(double, unsigned char decimalPlaces=2); </code></pre> <p>So if you don't want to have 2 decimal digits, you have to use <code>String(someFloat, 3)</code>.</p> <p>Also you have to remember there are limits for the floating point numbers, but in this case it shouldn't be the case.</p> <p>And as Edgar mentioned, String objects are bit dangerous if they are overused, particularly building that serverPath is the worst way how to do it (every single level of it creates new temp object to be copied into next bigger one and released).</p> <p>It would be cheaper to do it like:</p> <pre><code>String serverPath; serverPath.reserve(100); // reserve space so it doesn't have to resize; should be proper estimate serverPath += serverName; serverPath += &quot;?chip_id=&quot;; // on AVR it should be F() serverPath += chipId; serverPath += &quot;&amp;count1=&quot;; serverPath += new_count1; serverPath += &quot;&amp;count2=&quot;; serverPath += new_count2; serverPath += &quot;&amp;count3=&quot;; serverPath += new_count3; serverPath += &quot;&amp;count4=&quot;; serverPath += new_count4; serverPath += &quot;&amp;countgas=&quot;; serverPath += new_countgas; serverPath += &quot;&amp;countwater=&quot;; serverPath += new_countwater; </code></pre> <p>or you can use some c++ magic:</p> <pre><code>template &lt;class T&gt; inline String &amp; operator&lt;&lt;(String &amp; out, T const &amp; what) { out += what; return out; } String serverPath; serverPath.reserve(100); // reserve space so it doesn't have to resize serverPath &lt;&lt; serverName &lt;&lt; &quot;?chip_id=&quot; &lt;&lt; chipId &lt;&lt; &quot;&amp;count1=&quot; &lt;&lt; new_count1 &lt;&lt; &quot;&amp;count2=&quot; &lt;&lt; new_count2 &lt;&lt; &quot;&amp;count3=&quot; &lt;&lt; new_count3 &lt;&lt; &quot;&amp;count4=&quot; &lt;&lt; new_count4 &lt;&lt; &quot;&amp;countgas=&quot; &lt;&lt; new_countgas &lt;&lt; &quot;&amp;countwater=&quot; &lt;&lt; new_countwater; </code></pre> <p>this code takes <code>serverPath &lt;&lt; serverName</code> adds serverName into serverPath and the result is serverPath again, and then it continues as <code>serverPath &lt;&lt; &quot;?chip_id=&quot;</code> and so on</p>
89997
|arduino-uno|bluetooth|servo|hc-05|
Servo retaining its position every time I send some value
2022-06-24T09:59:56.930
<p>I wanted to control my servo with a Bluetooth module.</p> <p>I gave certain values for rotating it. When I press those values the servo rotates, but then retains its original position and the PC also makes the sound of the Arduino board disconnecting because I powered the board with my PC (tried with powerbank also). Even my Bluetooth disconnects.</p> <p>This is my code:</p> <pre><code>#include &lt;Servo.h&gt; Servo myservo; int pos = 0; char data = 0; void setup() { myservo.attach(9); Serial.begin(9600); } void loop() { if (Serial.available() &gt; 0) { data = Serial.read(); if (data == 'F') { // for (pos = 0; pos &lt;= 180; pos += 1) myservo.write(180); delay(1); } } else if (data == 'B') { // for (pos = 180; pos &gt;= 0; pos -= 1) myservo.write(0); delay(1); } } </code></pre> <p>Connections:</p> <p>Servo:</p> <pre><code>red wire -- 5 V (not working at 3.3 V) orange wire -- pin9 brown wire -- gnd </code></pre> <p>Bluetooth (hc05):</p> <pre><code>5 V -- 5 V gnd -- gnd rx -- tx tx -- rx </code></pre>
<p>I tried changing the USB B cable with a better quality one and it worked.</p>
90002
|library|audio|
Library fails to compile
2022-06-24T15:50:13.207
<p>I want to try out this library: <a href="https://github.com/connornishijima/arduino-volume3" rel="nofollow noreferrer">https://github.com/connornishijima/arduino-volume3</a></p> <p>I downloaded the zip file from github, renamed it, and included it as a library in the IDE.</p> <p>So run one of the examples, <code>A4_440HZ</code> This is its code:</p> <pre><code>#include &quot;Volume3.h&quot; #define speakerPin 9 uint16_t frequency = 440; void setup() { // Nothing neeeded here! } void loop() { for(uint16_t volume = 0; volume &lt; 1023; volume++){ vol.tone(speakerPin,frequency,volume); delay(1); } for(uint16_t volume = 1023; volume &gt; 0; volume--){ vol.tone(speakerPin,frequency,volume); delay(1); } } </code></pre> <p>And i get this error:</p> <pre><code>Error Compiling A4_440Hz.cpp.o: In function `loop': /usr/share/arduino/A4_440Hz.ino:12: undefined reference to `vol' /usr/share/arduino/A4_440Hz.ino:12: undefined reference to `vol' /usr/share/arduino/A4_440Hz.ino:16: undefined reference to `vol' /usr/share/arduino/A4_440Hz.ino:16: undefined reference to `vol' collect2: error: ld returned 1 exit status </code></pre> <p>I have no idea what is to blame, or how to mitigate it.</p> <p>This is the first time that an included example from a library does not play out of the box.</p>
<p>This is kind of a weird situation. The library declares the object <code>vol</code>, but fails to define it. On the ancient version of the Arduino IDE you are using, compilation fails, understandably, because <code>vol</code> has never been defined. What is weird is that, on a more recent version (1.8.15 on Ubuntu here), compilation succeeds.</p> <p>It is worth noting that <code>vol</code> belongs to the class <code>Volume</code>, which is an empty class. As such, it only plays the role of a namespace for the functions <code>vol.tone()</code> and <code>vol.noTone()</code>. Strictly speaking, as <code>vol</code> has no data (its size is zero), the compiler should never need to access it. My guess is that the newer Arduino manages to compile this only because it uses different optimization settings than the ancient 1.0.5.</p> <p>Anyhow, you have two options:</p> <ul> <li><p>upgrade your installation of the Arduino IDE</p> </li> <li><p>declare <code>Volume vol;</code> near the top of the sketch.</p> </li> </ul> <p><strong>Edit</strong>: I did some tests and it appears that, as I suspected, this is related to <a href="https://en.wikipedia.org/wiki/Interprocedural_optimization" rel="nofollow noreferrer">link-time optimization</a> (LTO). Since version 1.5.7, the Arduino IDE enables LTO, and when this is the case, the linker doesn't complain about missing empty objects.</p> <p>The library could be fixed by defining <code>vol</code> in Volume3.cpp, although this would create a weird empty object in the BSS. Another option would be to declare both methods as <code>static</code> within Volume3.h. This would make the compiler know it doesn't actually need to reference the <code>vol</code> object when one of its methods is called.</p> <p>Would you submit a pull request with one of those fixes?</p>
90009
|arduino-uno|serial|adc|isr|digital-analog-conversion|
Mildly accurate oscilloscope using Arduino Uno R3
2022-06-25T10:01:13.680
<p>I'm trying to make a mildly accurate oscilloscope using Arduino Uno R3 and I've done some research on the best method to do so. First of all I need to measure the voltage with a rather high sampling rate and then I'm going to transfer my data through the serial port and plot the data using Python or Matlab.</p> <p>According to what I have read the <code>analogread()</code> function will cause some delay and therefore some inaccuracies and thus it is not suitable for my purpose.</p> <p>I found on <a href="http://yaab-arduino.blogspot.com/2015/02/fast-sampling-from-analog-input.html" rel="nofollow noreferrer"><strong>this</strong></a> website some good info about how I should write my code, but I have some questions:</p> <ol> <li><p>I want my reference voltage to be 1.1 V so that by dividing it to 1023 parts I will have an accuracy of about 1 mV. How should I edit the mentioned code in order to do so?</p> </li> <li><p>The code in the <code>void loop()</code> setup is of no use to me (I prefer not to save the measured data on the Arduino and then send to my PC because of memory limitations). After deleting it will the data still be sent to the serial port?</p> </li> <li><p>Will sending the data through the serial port affect my sample rate/accuracy? I mean how does it effect my accuracy?</p> </li> </ol> <p>P.S: by mildly accurate this is what I mean: I want to measure voltage accurately with 1 mV precision for frequencies of max. 500 kHz (a bit less or more won't hurt).</p>
<blockquote> <p>I want my reference voltatge to be 1.1v so that by dividing it to 1023 parts I will have the accuracy of about 1mv.</p> </blockquote> <p>You will have a <em>resolution</em> of about 1 mV. The accuracy will be significantly worse than that due to the imperfections of the ADC (offset error, gain error, non-linearity) and noise.</p> <blockquote> <p>how should I edit the mentioned code in order to do so?</p> </blockquote> <p>The reference is configured by the bits <code>REFS0</code> and <code>REFS1</code> of the <code>ADMUX</code> register. The internal 1.1 V reference is selected by setting both bits, as shown in table 24-3 of <a href="https://ww1.microchip.com/downloads/aemDocuments/documents/MCU08/ProductDocuments/DataSheets/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061B.pdf#G3.1738867" rel="nofollow noreferrer">the datasheet</a>. You can then patch the original code like this:</p> <pre><code>@@ -8,7 +8,7 @@ ADCSRA = 0; // clear ADCSRA register ADCSRB = 0; // clear ADCSRB register ADMUX |= (0 &amp; 0x07); // set A0 analog input pin - ADMUX |= (1 &lt;&lt; REFS0); // set reference voltage + ADMUX |= (1 &lt;&lt; REFS0) | (1 &lt;&lt; REFS1); // set reference voltage ADMUX |= (1 &lt;&lt; ADLAR); // left align ADC value to 8 bits from ADCH register // sampling rate is [ADC clock] / [prescaler] / [conversion clock cycles] </code></pre> <blockquote> <p>the code in the <code>void loop()</code> setup is of no use for me (I prefer not to save the measured data on the arduino and then send to my pc because of memory limitations). after deleting it will the data still be sent to the serial port?</p> </blockquote> <p>In the linked code, <code>loop()</code> is the only function sending anything to the serial port. If you remove it, nothing will be sent. You could <code>Serial.write()</code> in the ISR though, in which case an empty <code>loop()</code> would be fine.</p> <p>Note that writing to <code>Serial</code> from within an ISR is generally discouraged. Your situation though (an oscilloscope code) is one of the very few cases where it does make sense to do so.</p> <blockquote> <p>will sending the data through the serial port affect my sample rate/accuracy?</p> </blockquote> <p>It can certainly affect your sampling rate. <code>Serial.write()</code> is usually non-blocking, as all it does is write the data to the RAM-based transmit buffer. If the buffer fills up, however, <code>Serial.write()</code> will block waiting for the serial port to actually send the data, and make enough room in the buffer.</p> <p>This means that, in order for the oscilloscope to not miss samples, you have to make sure that the serial port can send the data at least as fast as the ADC is acquiring it.</p> <p><strong>Example calculation</strong>: If you clock the ADC at 1 MHz, you get one sample every 13 µs. You can follow the example given in the code you linked to, and discard the last two bits in order to transmit only 8 bits of the sample. Transmitting those in plain binary will take 10 “bits” worth of the serial port bandwidth (one start bit, 8 data bits and one stop bit). Each bit should then take less than 1.3 µs, which translates to a baud rate of 769,231 bits per second. You will probably have no other choice than configuring the serial port for 1 Mb/s.</p> <p>If you want to transmit the whole 10 bits of the ADC readings, you will have to lower the sampling rate by a factor two.</p> <p>At this point you may notice that the serial port, rather than the ADC, is the bottleneck for the performance of your oscilloscope. If this is too limiting, you may consider building a scope that works by bursts: it stores a burst of samples in memory, then sends it at a leisurely rate through the serial port.</p>
90011
|arduino-nano|power|led|
Does an 5V 2.1 A will fit for this Led Schema?
2022-06-25T14:22:22.393
<p>Hello I would like to create an Arduino protoype with Led WS2182B. I currently have Arduino NANO (not UNO, like in this schema) 65 Led WS2182B = Which gives me 3.9 Amp of suply for full brighness (65*60mAmp) Power supply of a movil charge wich have 5V 2.1 A</p> <p>I am currently working with this schema from this <a href="https://core-electronics.com.au/guides/ws2812-addressable-leds-arduino-quickstart-guide/" rel="nofollow noreferrer">website</a></p> <p><a href="https://i.stack.imgur.com/rsZ5o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rsZ5o.png" alt="enter image description here" /></a></p> <p>I have a few questions</p> <ol> <li>Does this battery will work for this schema replacing the usb conector?</li> <li>Can I use the 68 leds at a medium energy, to make it suitable wih the power supply? Can this damage any device (Because in theory I believe it needs more than 2.1 Amps) 3)If this battery will not be appropiate to this schema. What could I do?</li> </ol> <p>Thank you very much!</p>
<p>You are using a standard USB power bank. It should be possible to power your project as long as you stay below the current limit (2.1A). Probably you should keep the intensity small enough to not exceed 1.9A in normal operation. That should be enough for about half intensity. You really don't want to exceed the current limit. And you should measure the actual current draw and then approach your own current limit (like 1.9A) from below. Calculations are good, but when operating like this you should look at the real values.</p> <p>If you exceed the current limit of the power bank it depends on the implementation of the power bank what will happen. Most likely the power bank will cut the power but still work. Though it is also possible, that you fry some electronics inside the power bank and kill it this way.</p> <p>Note:</p> <ul> <li>While you experiment with your code you can use fewer LEDs, so that they would be able to light up at full intensity. That makes sure, that you don't damage anything from a small programming error. If you write your code in the correct way (for example defining the number of LEDs at exactly one code line and reusing that name everywhere), then it will be easy to increase the number of LEDs to the target and also be sure, that you are staying within your limits.</li> <li>You already have it in your wiring diagram, but nonetheless I want to emphasize, that you must not power the LEDs through the Arduino. You need to connect them directly to the USB cable to the power bank. The Arduino cannot withstand such currents.</li> <li>USB power banks often cut power, when not enough current is being drawn from them (and for mine the current of an Arduino Nano wasn't enough to hold it active). If in your project the LEDs get turned of at some time, while the Arduino should keep running, the power bank might cut the power, thus turning off the Arduino. In my experience the bigger, more expensive power banks will do that, while small, cheap ones will just keep outputting the power. If this scenario is relevant for you, you need to test this yourself with your specific power bank.</li> </ul> <blockquote> <p>If this battery will not be appropiate to this schema. What could I do?</p> </blockquote> <p>You could use multiple of these power banks, each of them powering its own part of the LED strip. One of them can also power the Arduino. Just make sure to connect all grounds together.</p>
90018
|arduino-uno|usb|joystick|simulator|
Can I make an Arduino Uno Rev3 pretend to be a joystick?
2022-06-26T10:26:50.520
<p>I want to create a joystick for my flight simulator and I need to make an Arduino Uno Rev3 pretend to be a joystick when I plug it to my computer.</p>
<p>The Uno doesn't have native USB capabilities. It uses an additional microcontroller (the Atmega16u2) as an USB to Serial adapter. In the default configuration this microcontroller is only programmed for providing a serial interface over USB, not a joystick interface. You can hack your Uno and reprogram the Atmega16u2 for providing a joystick interface (and there are tutorials for how to reprogram the Atmega16u2 online). (Note, that you need a genuine Arduino for this to work, since the cheap clones often only have CH430 chips as USB to Serial adapter)</p> <p>But I would suggest going the easier way and buying an Arduino board, which itself has USB capabilities without the need of hacking the board, like the Arduino Micro. Then you can simply use one of the joystick libraries on it. This way will be a lot easier for a beginner than doing it with an Uno.</p>
90023
|pwm|timers|hardware|teensy|
Teensy 4.1 / 4.0 When to use FlexPWM vs QuadTimer pins to strobe LEDs
2022-06-26T18:12:25.027
<p>I want to strobe 3 LEDs (at independent frequencies and duty cycles) via mosfets with a duty cycle of 0.05%-1% at a frequency range of 24-100 hz. I would like to hold 1% or better accuracy for both duty cycle and frequency.</p> <p>The Teensy 4.x seems perfect with its amazing PWM frequency and resolution controls, and generous number of independent PWM timers.</p> <ol> <li>For the purposes of my application, should I use pins with FlexPWM or QuadTimer? Does it matter?</li> <li>I see that the numbering convention is X.Y, is there any functional significance when X numbers are in common (IE FlexPWM 1.0 and FLexPWM 1.1)?</li> </ol> <p><a href="https://www.pjrc.com/teensy/td_pulse.html" rel="nofollow noreferrer">See &quot;Frequency&quot; section of this page</a></p>
<p>I had cross-posted, and Paul Stoffregen answered <a href="https://forum.pjrc.com/threads/70530-Teensy-4-1-4-0-When-to-use-FlexPWM-vs-QuadTimer-to-strobe-LEDs?p=308324#post308324" rel="nofollow noreferrer">in the Teensy Forum</a>. Pasting Paul's great answer here for posterity:</p> <blockquote> <p>1: Really doesn't matter for 0.05% accuracy.</p> <p>2:See &quot;PWM Frequency&quot; on <a href="https://www.pjrc.com/teensy/td_pulse.html" rel="nofollow noreferrer">this page.</a></p> <p>The 3 pins identified as &quot;FlexPWM1.0&quot; (1, 44, 45) will always run at the same frequency. If you want different PWM frequency, you would need to choose pins from different groups.</p> <p>More detail on how the hardware actually works can be found in the reference manual. But usually that ends of being far too much information. The timers are packed with a mind boggling number of advanced features, which makes a steep learning curve if you want to dive into how the hardware really works.</p> <p>Most applications work fine by simply using analogWrite, analogWriteResolution and analogWriteFrequency. Everything you've said sounds like a pretty simple application that can be done easily with these 3 functions. You're only looking for 9 bit resolution from hardware than is natively 15 or 16 bits. Just use the easy functions do the low-level work for you.</p> </blockquote>
90043
|interrupt|
`noInterrupts()` causes the arduino to no longer appear in ports
2022-06-29T10:49:36.163
<p>Minimal working example:</p> <pre><code>void setup() { // initialize digital pin LED_BUILTIN as an output. noInterrupts(); 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>When uploaded to my Arduino Nano 3.3v BLE from my M1 Mac, this causes the Nano to no longer appear in the ports menu. In order to get it to appear again, I have to double press the reset button on the Nano so that it resets to a default script. After doing this, the Nano is available in the ports menu again.</p> <p>I also cannot see the Nano via <code>cat /dev/cu.&lt;TAB&gt;</code> when this script is uploaded to it.</p> <p>Does anyone know why this happens? Or alternatively (if this is intended behaviour) why it is not documented in <a href="https://www.arduino.cc/reference/en/language/functions/interrupts/interrupts" rel="nofollow noreferrer"><code>interrupts()</code></a> or <a href="https://www.arduino.cc/reference/en/language/functions/interrupts/nointerrupts" rel="nofollow noreferrer"><code>noInterrupts</code></a>?</p> <p>I've looked through some other posts, but I don't think they're duplicates of this one:</p> <ul> <li><a href="https://arduino.stackexchange.com/questions/61567/what-functions-are-disabled-with-nointerrupts">What functions are disabled with noInterrupts()?</a>: doesn't highlight the behaviour I've seen in the MWE.</li> <li><a href="https://arduino.stackexchange.com/questions/35358/trying-to-understand-interaction-of-interrupts-nointerrupts-and-delays">Trying to understand interaction of interrupts, noInterrupts and delays</a>: Gives interesting techniques for interrupts and embedded programming, but doesn't mention the behaviour I've seen</li> </ul> <h4>Edits in response to answers</h4> <p>So the MWE wasn't quite descriptive enough of my problem and some of the answers got caught up on that (which is my fault). I've included a more detailed description of what I'm doing below to describe what I'm actually doing, but I've also accepted the answer which I think answers the heart of the question &quot;why do interrupts cause the Nano to not appear in port?&quot;.</p> <p>What I'm actually doing is I've got two Arduino Nanos (call them primary and secondary) connected via I2C and <code>Wire.h</code>. Each Arduino nano is reading 15 analog inputs (via a multiplexer). The secondary Nano is then sending its 15 analog readings to the primary over I2C. But I'm getting a lot of noise in the analog readings of the primary Nano, but no noise in the secondary. This noise disappears when I disconnect I2C. So my theory was that digital SCL and SDA wires were causing noise in the analog sensor wires, but I observed the noise would only occur for ~2ms every ~10ms. I thought I'd disable interrupts (and therefor disable <code>Wire.h</code> from pulsing SCL/SDA) while I was reading the primary's analog sensors, and enable interrupts afterwards. This caused the Nano to not appear in the Ports tab, and the rest is the result of this post.</p> <p>I now think I didn't include the 4.7Ohm pull-up resistor on SDA and SCL which seems to only be included on the official Arduino examples, and never on any random internet examples.</p>
<p>I'm not really an expert on the Nano 3.3v BLE, however it appears that it is directly connected to the USB port and thus disabling interrupts will also disable its ability to respond to USB handshakes, thus it will appear to the host that it has been unplugged.</p> <p>The original Nano had a separate chip (FT232RL) which handled the USB interface, and thus disabling interrupts on that Arduino would not drop the USB connection.</p> <blockquote> <p>Or alternatively (if this is intended behaviour) why it is not documented in interrupts() or noInterrupts?</p> </blockquote> <p>Probably the documentation has not kept up-to-date with later product releases. It is not uncommon for documentation to lag behind what the released products actually do.</p> <p>As timemage points out in another answer, your attempts to blink LEDs with interrupts turned off will not succeed. In fact, turning interrupts off should only be done for milliseconds, not permanently. I assume that is a demonstration sketch, but still ... if you turn interrupts off only briefly the problem should go away.</p>
90046
|avr|avrdude|avr-gcc|avr-toolchain|
How do I build and upload a C++ program without the Arduino Library or IDE?
2022-06-29T14:37:50.603
<p><em>Note: This is a reference question (but feel free to write answers of your own!)</em></p> <hr /> <p>I want to use the AVR tools directly -- no arduino-builder or arduino-cli. I would also like compilation and uploading to be as fast as reasonably possible</p>
<ol> <li>Create a new file called <code>Makefile</code> in your project directory. Populate it with the following contents:</li> </ol> <pre><code>TEMPDIR := $(shell mktemp -d) all: avr-g++ -DF_CPU=&lt;CLK&gt; -mmcu=&lt;PARTNO&gt; -fno-threadsafe-statics -O3 -flto -std=c++23 -isystem/usr/avr/include -lm -fuse-linker-plugin -Wl,--gc-sections *.cpp -o ${TEMPDIR}/a.elf avr-objcopy -O ihex -R .eeprom ${TEMPDIR}/a.elf ${TEMPDIR}/a.hex avrdude -V -p&lt;PARTNO&gt; -carduino -P/dev/tty&lt;SERIAL_PORT&gt; -b&lt;BAUD&gt; -D -Uflash:w:${TEMPDIR}/a.hex rm ${TEMPDIR}/a.elf ${TEMPDIR}/a.hex rm -d ${TEMPDIR} </code></pre> <ol start="2"> <li>In the Arduino IDE, press <kbd>Ctrl</kbd>+<kbd>,</kbd> and enable verbose output during compilation and uploading.</li> <li>Start uploading with <kbd>Ctrl</kbd>+<kbd>U</kbd>. Replace the groups of angled brackets in Makefile (e.g. <code>&lt;CLK&gt;</code>) with the values in the Arduino IDE's build output.</li> <li>Run <code>make</code>.</li> </ol> <p><code>-lm</code> links in the AVR math library. <code>*.cpp</code> refers to your c++ source files. <code>-V</code> prevents avrdude from reading back the flash contents and verifying it, which saves time, but you may want to disable it while diagnosing problems.</p>
90049
|bootloader|reset|watchdog|
How do I escape a boot loop?
2022-06-29T15:43:38.963
<p><em>Note: This is a reference question (but feel free to write answers of your own!)</em></p> <hr /> <p>I uploaded code that contains a bug that causes my Arduino to immediately reset itself when starting using <a href="https://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_softreset" rel="nofollow noreferrer">this</a> code from the AVR libc FAQ. The built-in LED keeps flashing. Because it's in this state of constantly resetting, I'm unable to upload my sketch to it.</p> <p>I tried holding the reset button while uploading and burning a new bootloader, but neither of those worked.</p> <p>How do I get my Arduino out of this boot loop so I can upload sketches again?</p>
<ol> <li>Start holding the reset button. This is to prevent the Arduino from entering the boot loop.</li> <li>Unplug the Arduino and plug it back in.</li> <li>Open a new sketch. Remove all of the code and replace it with <code>int main(){}</code>. This is to create a small program that will upload quickly.</li> <li>Start uploading the sketch. Avrdude will attempt to upload the sketch ten times -- each time it tries, the RX LED on the Arduino will flash briefly.</li> <li>Notice how often the LED flashes (0.2 Hz for me). Right before it flashes again, release the reset button. There's a small window of oppurtunity for avrdude to upload the sketch before the arduino starts up. If the TX and RX LEDs flash, success!</li> </ol>
90061
|bootloader|arduino-as-isp|
How do I upload a sketch without a bootloader, using another Arduino as a programmer?
2022-06-30T21:26:45.190
<p><em>Note: This is a reference question (but feel free to write answers of your own!)</em></p> <hr /> <p>My Arduino takes too long to start up, I need to use the space taken up by the bootloader and I don't want a brown-out to be able to move the program counter to bootloader code, which could lead to my code being corrupted.</p> <p>I considered buying an Arduino programmer, but since I already have an Uno lying around doing nothing, I would rather use that as a programmer.</p> <p>I found a few guides on the internet, but most of them leave important details out and aren't specific enough.</p> <p>So, how can I upload a sketch without a bootloader, using another Arduino as a programmer?</p>
<p>There are a few guides on the internet that explain how to do this, but I've found that most of them contain too much ambiguity or leave important details out. This is my attempt at writing a short but complete guide that's easy to follow.</p> <h2>Prerequisites</h2> <ul> <li>The board that will run your sketch</li> <li>A board that will act as a programmer (a.k.a. &quot;ISP&quot;)</li> <li>7 wires</li> <li>Any small capacitor</li> </ul> <h2>Steps</h2> <h3>Programming the programmer</h3> <p>First, you'll need to upload the ArduinoISP sketch to the programmer. Here's how:</p> <ol> <li>In the Arduino IDE, press <kbd>Alt</kbd>+<kbd>F</kbd> and open Examples -&gt; 11.ArduinoISP -&gt; ArduinoISP.</li> <li>Plug in the programmer board (USB).</li> <li>Press <kbd>Alt</kbd>+<kbd>T</kbd> and set &quot;Board&quot; to your <em>programmer</em> board's type and &quot;Port&quot; to your <em>programmer</em> board's serial port.</li> <li>Press <kbd>Ctrl</kbd>+<kbd>U</kbd> to upload the sketch to your programmer.</li> </ol> <h3>Connecting the boards</h3> <p>Then you need to connect the programmer to the board that will run your sketch.</p> <ol> <li>Unplug the programmer board. This is to prevent accidental short-circuits.</li> <li>Connect pins <strong>GND, 10, MOSI, MISO, SCK and 5V</strong> of the programmer to pins <strong>GND, RESET, MOSI, MISO, SCK and 5V</strong> of the board that will run your sketch, respectively. Pins MOSI, MISO and SCK correspond to pins 11, 12 and 13, respectively, on the Uno and the Nano. Consult your board's datasheet if you're uncertain.</li> <li>Connect the capacitor between pins 5V and RESET of the programmer board. This is to prevent it from auto-resetting while programming.</li> <li>Plug in the programmer board. You will never need to plug in the board that will run your sketch.</li> </ol> <h3>Uploading your sketch</h3> <p>The order of these steps is important due to a bug in the Arduino IDE.</p> <ol> <li>Press <kbd>Alt</kbd>+<kbd>T</kbd> and set &quot;Board&quot; to <em>the board that will run your sketch</em>'s type, &quot;Port&quot; to your <em>programmer</em> board's serial port and &quot;Programmer&quot; to &quot;Arduino as ISP&quot;.</li> <li>Open the sketch you would like to upload.</li> <li>Press <kbd>Ctrl</kbd>+<strong><kbd>Shift</kbd></strong>+<kbd>U</kbd> to upload the sketch using the programmer.</li> </ol> <h2>Troubleshooting</h2> <p>If something went wrong, press <kbd>Ctrl</kbd>+<kbd>,</kbd> and enable verbose &quot;compilation&quot; and &quot;upload&quot; and repeat the step that went wrong. Look out for these error messages:</p> <h3><code>avrdude: stk500_recv(): programmer is not responding</code></h3> <p>Followed by something similar to:</p> <pre><code>avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00 avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0 </code></pre> <p>Remove the capacitor before uploading a sketch to your <em>programmer</em> board.</p> <h3><code>avrdude: Yikes! Invalid device signature.</code></h3> <p>Scroll up and copy the line that looks similar to the following:</p> <pre><code>...avrdude -C...avrdude.conf -v -V -p... -c... -P... -b... -Uflash:w:....hex:i </code></pre> <p>Paste it into a terminal and add <code> -F</code> to the end. You can reuse this command every time you upload the same sketch.</p> <h3>The upload seems to succeed but my sketch is still running the same code!</h3> <p>If the board that runs your sketch's CPU clock is slower than 1MHz (e.g. your sketch modifies the CPU prescaler), you need to change <code>(1000000/6)</code> in the ArduinoISP sketch to something slower and re-upload the sketch to your programmer.</p>
90066
|flash|arduino-nano-33-iot|
Arduino Nano IOT33 - Using flash
2022-07-01T12:42:58.237
<p>I'm looking for a way to store data on flash as on ESP8266 or ESP32 using <code>FS.h</code>, <code>LITTLEFS.h</code> but it fails.</p> <p>Is is possible on Nano IOT33 ?</p>
<p>It seems this library can be used:</p> <p><a href="https://github.com/cmaglie/FlashStorage" rel="nofollow noreferrer">https://github.com/cmaglie/FlashStorage</a></p> <p>Library: FlashStorage library for Arduino</p> <p>About info: A convenient way to store data into Flash memory on the ATSAMD21 and ATSAMD51 processor family</p> <p>Mentioned in external related article (thanks to Juraj): <a href="https://forum.arduino.cc/t/persistent-storage-for-arduino-nano-33-iot-no-eeprom/623137" rel="nofollow noreferrer">https://forum.arduino.cc/t/persistent-storage-for-arduino-nano-33-iot-no-eeprom/623137</a></p> <p><strong>UPDATE</strong></p> <p>(See remark of Juraj below: this is NOT for a Nano IOT33)</p> <p>See Library: <a href="https://github.com/khoih-prog/FS_Nano33BLE" rel="nofollow noreferrer">https://github.com/khoih-prog/FS_Nano33BLE</a></p> <p>About info: Wrapper of FS (LittleFS or not-advisable FATFS) for Arduino MBED nRF52840-based boards, such as Nano_33_BLE boards. This library facilitates your usage of FS (LittleFS or FATFS) for the onboard flash. FS supports power fail safety and high performance</p> <p>Mentioned in: <a href="https://forum.arduino.cc/t/fs-nano33ble-library-for-nano-33-ble-using-littlefs-fatfs/900463" rel="nofollow noreferrer">https://forum.arduino.cc/t/fs-nano33ble-library-for-nano-33-ble-using-littlefs-fatfs/900463</a></p>
90071
|arduino-uno|usb|data|logging|
How can I log data to a thumb drive?
2022-07-02T11:26:49.953
<p>I am working on a project where I need to log data, but I was wondering if it is possible to log that data to a thumb drive? I know that I can log data to an SD card, but I thought a thumb drive would be more accessible to users who wish to obtain the data. And if it is possible to log to a thumb drive, could it be done in CSV format? The data is just sensor data.</p>
<p>[Updated]</p> <p>As an alternative to a Uno host shield, changing to a different Arduino MCU may also assist. USB host capabilty is needed for communicating with thumb drives.</p> <p><a href="https://forum.arduino.cc/t/how-to-tell-if-a-board-has-native-usb-support-for-a-midi-project-with-a-mac/667494" rel="nofollow noreferrer">Some Arduino models</a> have a native USB port (e.g., Arduino Due, Arduino Leonardo, Arduino Micro, Arduino Nano 33 IOT, Arduino Zero, Arduino MKR Zero, Arduino MKR1000 ... ) which will work as a USB client device role.</p> <p>A smaller set of MCU can act as either a USB client or host (e.g., Arduino Due, Arduino Portenta, ...). There is a <a href="https://www.arduino.cc/reference/en/libraries/usbhost/" rel="nofollow noreferrer">USBHost</a> library for Arduino Due listed in the Arduino Reference. Documentation for Arduino Portenta in USB host mode is <a href="https://docs.arduino.cc/tutorials/portenta-h7/usb-host" rel="nofollow noreferrer">here</a>.</p> <p><a href="https://forum.arduino.cc/t/usb-host-due-support-for-mass-storage-devices-thumbdrives/635331" rel="nofollow noreferrer">Here</a> is a discussion (and reference to an alternative library) regarding using a Due to write files to a thumb drive.</p> <p>Of course an adapter cable or a thumb drive with a physical connector matching the native USB port on the selected MCU is required. Both are commonly available.</p> <p>See also <a href="https://arduino.stackexchange.com/questions/24177/can-the-arduino-interface-with-usb-devices-without-the-usb-host-shield">Can the Arduino interface with USB devices without the USB host shield?</a></p>
90073
|esp32|reset|ntpclient|
ESP32, NTP and SW reset
2022-07-02T13:40:46.690
<p>After HW reset (button or power reconnect) I get the correct NTP shift, but when I use <code>ESP.restart()</code> via MQTT I get the correct time without 3 3 HRS shift due to Tz. What happens after SW reset that behaves in such manner and how to fix it?</p> <pre><code>bool myIOT2::_startNTP(const char *ntpServer, const char *ntpServer2) { unsigned long startLoop = millis(); while (!_NTP_updated() &amp;&amp; (millis() - startLoop &lt; 20000)) { #if defined(ESP8266) configTime(TZ_Asia_Jerusalem, ntpServer2, ntpServer); // configuring time offset and an NTP server #elif defined(ESP32) configTzTime(TZ_Asia_Jerusalem, ntpServer2, ntpServer); #endif delay(1000); } if (!_NTP_updated()) { return 0; } else { return 1; } } bool myIOT2::_NTP_updated() { return now() &gt; 1640803233; } </code></pre>
<p>Apparently, time in ESP32 survives a sw reset, while in ESP8266 doesn't. So in code, which is same for both - if clock is updated (a rough criteria that time is greater than some day in 2020 ), it skipped TZ update <code>configTzTime(TZ_Asia_Jerusalem, ntpServer2, ntpServer);</code></p> <p>So after a crash and/or sending a MQTT message to reboot, time was missing TZ update.</p> <p>Hope it'll help someone.</p> <p>Guy</p>
90075
|compile|code-optimization|keyboard|digispark|
How to cut down size of imported DigiKeyboard library
2022-07-03T09:03:02.523
<p>I'm working on a project with a Digispark ATTiny85, that performs keystrokes using the DigisparkKeyboard library (<a href="https://github.com/digistump/DigisparkArduinoIntegration/tree/master/libraries/DigisparkKeyboard" rel="nofollow noreferrer">https://github.com/digistump/DigisparkArduinoIntegration/tree/master/libraries/DigisparkKeyboard</a>). Besides the DigiKeyboard, I also import EEPROM.h.</p> <p>My own code is only about 150 lines, I've cut down the size following a number of online guides, trying to avoid larger data types and so on. The Digispark is limited to ~6kB and the imported DigiKeyboard library takes up a little more that 5.4kB. In total the compiled project takes up about 7kB, which exceeds the boards capacity.</p> <p>From the DigiKeyboard library I only use <code>DigiKeyboard.sendKeyStroke()</code> and <code>DigiKeyboard.print()</code> (with about only ten different characters). So I assume there is a lot of unused code I could remove, but I don't know how to approach this. I use Visual Studio Code and PlatformIO.</p> <p>How could I reduce the size of the used DigisparkKeyboard library?</p>
<p>With input from @EdgarBonet, I looked into the functions used and it turned out that the <code>String()</code> function, I used once in my code, takes up about 3kB of space in the compiled program.</p> <p>I ended up removing the line with <code>String()</code> and kept the imported DigiKeyboard library as it is.</p>
90089
|atmega328|avr|eeprom|
How does erasing the EEPROM work?
2022-07-04T15:54:42.113
<p>The datasheet for the ATmega328P contains this table, which describes bits 4 and 5 of EECR:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>EEPM1</th> <th>EEPM0</th> <th>Programming Time</th> <th>Operation</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>0</td> <td>3.4ms</td> <td>Erase and write in one operation (atomic operation)</td> </tr> <tr> <td>0</td> <td>1</td> <td>1.8ms</td> <td>Erase only</td> </tr> <tr> <td>1</td> <td>0</td> <td>1.8ms</td> <td>Write only</td> </tr> </tbody> </table> </div> <p>I'm currently working on some non-blocking EEPROM-handling code and I'm wondering when and how I should erase the EEPROM.</p> <ul> <li>What does erasing do? Does it set one byte to 0x0, or the entire EEPROM?</li> <li>Should I erase it first whenever I want to write a byte? <ul> <li>If not, why is there an option to erase and write separately?</li> </ul> </li> <li>How do I initiate an erase?</li> </ul> <p>Either the datasheet is rather lacking concerning the EEPROM, or I'm just not finding what I'm looking for. I tried using a search engine, but all results are either about the Arduino EEPROM library or &lt;avr/eeprom.h&gt;, both of which use polling instead of interrupts (and are therefore blocking).</p>
<p>I switched to FRAM, 32K x 8 can be gotten for just a few $$$, generally less the imported Arduinos. It is as fast as the Arduino can access it, both read and write. You can use I2C or SPI depending on which unit you buy. There are some very nice libraries for it making it easy to use. It is non volatile, ie does not lost information when power fails. It will support in the range of a trillion memory cycles with no delay when writing or reading it so no blocking. Just a few extra processor cycles because of the SPI or I2C overhead. If you have code already written for the External EEPROM it should work as is but it will have an unneeded delay in it.</p>
90097
|lcd|rtc|arduino-mini|
How can I use a LCD I2C and a RTC3231 on a Arduino Pro Mini?
2022-07-06T02:08:49.097
<p>On a small project, I have a DS3231 RTC module and a LCD I2C module that I'm trying to connect on a Arduino Pro Mini board. However, both the RTC and LCD require connecting the <code>SDA</code> and <code>SCL</code> to the pins <code>A4</code> and <code>A5</code> respectively.</p> <p>The libraries do not seem to allow changing the connected pins. Why is that? I have other pins available, like <code>A6</code> and <code>A7</code>, can those be used?</p>
<p>Welcome, I understand where you are coming from, without a background you do not know what to ask. Were were all where you are at one time. I hope this helps. You need to do some studying on the I2C bus, online tutorials will make it easy. You you will find you can connect over 100 devices to it at one time The SCL and SDA lines go from module to module. Note each module has its own address, sometimes they are selectable. Some modules have pull up resistors, others do not. To keep it interesting the pull up resistors are mostly 10K but that is not a constant.</p> <p>There are loading rules etc to be careful of if you have long wires or maybe more than three units. You need to add pull ups to each of the two lines (example: 4.7K from SCL to +5) or use something in the 3K range for a 3V3 system. The reason is because the bus has both dominant and recessive states where the recessive is high which the resistor provides. The SCL and SDA output/input on the parts have open collector/open drain outputs so they cannot source anything.</p> <p>Once you have it hooked up you need to run a program called I2C scan or something like that. If you have wired it correctly it will give you the address of the module, you will probably get two or three as there is the RTC, Memory device and possible a temperature sensor.</p> <p>The #1 rule is the Arduino A Power Supply it is NOT! A small module or two connected to the 5V out is fine but never connect a motor directly to any arduino you will probably fry the Arduino.</p> <p>I use Vin and supply it with about 8 volts by using either a Buck or Sepic converter from a 12V 2A or larger supply. I do it this way because I get a more stable voltage on the Arduino because of the extra filtering etc built into the analog regulator section. Real nice when using the A/D, keeps things stable. Were here to help, ask questions any time and do not worry is some over eager person decides to vote you down. Read the guidelines etc and you will do great.</p> <p>You can search online for &quot;Arduino RTC&quot; and find a lot of programs with software.</p>
90116
|arduino-uno|lcd|button|
Problem with push button
2022-07-07T21:39:27.903
<p>I am making a project where if the push button is pressed, the LCD screen will show a message. But with many trial and errors, it doesn't give the right result.</p> <p>Here is the circuit: <a href="https://i.stack.imgur.com/zhv7W.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zhv7W.jpg" alt="" /></a></p> <p>Here is the code:</p> <pre><code>#include &lt;LiquidCrystal.h&gt; // initialize the library by associating any needed LCD interface pin // with the arduino pin number it is connected to const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2; LiquidCrystal lcd(rs, en, d4, d5, d6, d7); #define BUTTON 7 void setup() { // set up the LCD's number of columns and rows: lcd.begin(16, 2); pinMode(BUTTON, INPUT); } void loop() { // set the cursor to column 0, line 1 // (note: line 1 is the second row, since counting begins with 0): lcd.setCursor(0, 0); // print the number of seconds since reset: lcd.print(&quot;Press Button&quot;); lcd.setCursor(0,1); lcd.print(&quot;to make COFFEE&quot;); if (digitalRead(BUTTON) == HIGH) { lcd.clear(); lcd.print(&quot;SENT TO MACHINE&quot;); } } </code></pre>
<p>It looks like you have several issues.</p> <ol> <li><p>The positive and negative supply &quot;rails&quot; on your prototyping board are not connected together internally. You should add a positive jumper wire.</p> </li> <li><p>You are trying to detect when the button provides a <code>HIGH</code> logic level, but there is no possibility of doing so with the current &quot;wiring&quot;.</p> </li> </ol> <p>One more thing that could help to determine this, or another possible issue, is a picture of your setup from a different angle so we can see exactly how that button, capacitor, and resistor are connected.</p> <p>This is the area which would be nice to see from a different angle.</p> <p><a href="https://i.stack.imgur.com/Vq3G8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vq3G8.jpg" alt="enter image description here" /></a></p>
90119
|arduino-uno|esp8266|wifi|http|
POST request (HTTPClient) with ESP8266 not working on localhost (http code = -1)
2022-07-08T09:15:00.710
<p>I've been looking around for a solution, but couldn't manage to find one. I'm looking to send a post request from an ESP8266 on a local API. Here is my code :</p> <pre><code>#include &lt;ESP8266WiFi.h&gt; #include &lt;ESP8266HTTPClient.h&gt; #include &lt;WiFiClient.h&gt; String ssid = &quot;HUAWEI P30 lite&quot;; String password = &quot;testazerty&quot;; String serverName = &quot;http://192.168.56.1:3030/drink/voltron&quot;; void setup() { Serial.begin(115200); WiFi.begin(ssid, password); Serial.println(&quot;Connecting&quot;); while(WiFi.status() != WL_CONNECTED) { delay(500); Serial.print(&quot;.&quot;); } Serial.println(&quot;&quot;); Serial.print(&quot;Connected to WiFi network with IP Address: &quot;); Serial.println(WiFi.localIP()); } void loop() { if(WiFi.status()== WL_CONNECTED){ WiFiClient client; HTTPClient http; http.begin(client, serverName); http.addHeader(&quot;Content-Type&quot;, &quot;application/json&quot;); int httpResponseCode = http.POST(&quot;{\&quot;city\&quot;:\&quot;toronto\&quot;}&quot;); Serial.print(&quot;HTTP Response code: &quot;); Serial.println(httpResponseCode); http.end(); } } </code></pre> <p>Both my computer and ESP8266 are connected to my phone network (HUAWEI).</p> <p>192.168.56.1 is the IP of my computer.</p> <p>API is running, and I can successfully make the request from postman (see image below).</p> <p><a href="https://i.stack.imgur.com/CdfNb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CdfNb.png" alt="enter image description here" /></a></p> <p>It always return -1 as http code. I activated debug level HTTP_CLIENT, here is what I have on the serial monitor :</p> <pre><code>11:07:41.645 -&gt; SDK:2.2.2-dev(38a443e)/Core:3.0.2=30002000/lwIP:STABLE-2_1_2_RELEASE/glue:1.2-48-g7421258/BearSSL:6105635 11:07:41.645 -&gt; fpm close 1 11:07:41.645 -&gt; mode : sta(30:83:98:b1:da:62) 11:07:41.645 -&gt; add if0 11:07:41.645 -&gt; Connecting 11:07:42.160 -&gt; .....scandone 11:07:45.348 -&gt; state: 0 -&gt; 2 (b0) 11:07:45.348 -&gt; .state: 2 -&gt; 3 (0) 11:07:45.441 -&gt; state: 3 -&gt; 5 (10) 11:07:45.441 -&gt; add 0 11:07:45.441 -&gt; aid 6 11:07:45.441 -&gt; cnt 11:07:45.441 -&gt; 11:07:45.441 -&gt; connected with HUAWEI P30 lite, channel 6 11:07:45.441 -&gt; dhcp client start... 11:07:45.864 -&gt; ....ip:192.168.43.88,mask:255.255.255.0,gw:192.168.43.1 11:07:47.870 -&gt; . 11:07:47.870 -&gt; Connected to WiFi network with IP Address: 192.168.43.88 11:07:47.870 -&gt; [HTTP-Client][begin] url: http://192.168.56.1:3030/drink/voltron 11:07:47.870 -&gt; [HTTP-Client][begin] host: 192.168.56.1 port: 3030 url: /drink/voltron 11:07:47.870 -&gt; [HTTP-Client][sendRequest] type: 'POST' redirCount: 0 11:07:53.021 -&gt; [HTTP-Client] failed connect to 192.168.56.1:3030 11:07:53.021 -&gt; [HTTP-Client][returnError] error(-1): connection failed 11:07:53.021 -&gt; HTTP Response code: -1 11:07:53.021 -&gt; [HTTP-Client][end] tcp is closed </code></pre>
<p><strong>TLDR</strong>:</p> <p>This is a networking problem, not a programming problem. Try changing your subnet mask to 255.255.0.0 on your router/network configuration, or make sure they're actually connected to the same router. If different routers, try to change one to a &quot;Wireless Access Point&quot; configuration. If you can't get them on the same network, you will have to expose your API to the Internet.</p> <p><strong>Long version:</strong></p> <p>You are on different subnets. Your API IP address is 192.168.56.1 and your device IP address is 192.168.43.88, but your subnet mask is 255.255.255.0. That puts these devices on separate subnets within the network.</p> <p>There are a lot of complicated explanations of subnets and subnet masks on the internet. I linked one of the better ones below. Technically, you are not just on different subnets but on different networks entirely. You have a 192.x.x.x IP address, making it a Class C network. That makes your address pattern one of &quot;network.network.network.node&quot;. Depending on your router configuration or other network hardware, you can upgrade it to a Class B network by customizing your subnet mask as 255.255.0.0 (&quot;network.network.node.node&quot;). Class B addresses might require a lot of customization on your end depending on your specific circumstances. By using a subnet mask of 255.255.0.0 on a Class B address, you classify the IP address parts .56.1 and .43.88 as being on the same network AND subnet. If you change it to Class B addressing without changing the subnet, the .56 will be one subnet and .43 will be a different subnet.</p> <p>Sometimes this addressing is done automatically based on the installed hardware. This is especially problematic in home networks containing multiple wireless routers but connected to the same modem. Many home routers have a &quot;Wireless Access Point&quot; setting that removes a lot of the more complex router configuration. This <em>might</em> convince your router(s) to put you onto the same subnet. If that works, you now have your devices able to connect locally! Additional router configuration might be required to expose ports for your API to incoming requests across subnets.</p> <p>If your network class is being determined by your ISP and you can't get your devices onto the same network, you have to expose your API to the Wild Wild Web :D There are many services which allow for Dynamic DNS, but I'd suggest reading through <a href="https://www.ionos.com/digitalguide/server/tools/free-dynamic-dns-providers-an-overview/" rel="nofollow noreferrer">https://www.ionos.com/digitalguide/server/tools/free-dynamic-dns-providers-an-overview/</a> and selecting one that meets your needs. This WILL require advanced router configuration to expose ports to the internet. <em>Please select a Dynamic DNS services that provides DDOS protection.</em> Once it is exposed, your ESP8266 can hit your API as it would any public API. <em>Please put authentication on your API.</em></p> <p>References:</p> <ul> <li>Subnet explanation - <a href="http://www.steves-internet-guide.com/subnetting-subnet-masks-explained/" rel="nofollow noreferrer">http://www.steves-internet-guide.com/subnetting-subnet-masks-explained/</a></li> <li>Dynamic DNS providers - <a href="https://www.ionos.com/digitalguide/server/tools/free-dynamic-dns-providers-an-overview/" rel="nofollow noreferrer">https://www.ionos.com/digitalguide/server/tools/free-dynamic-dns-providers-an-overview/</a></li> </ul>
90120
|arduino-uno|communication|rf|serial-data|
Noise in RF 434 transmitter and receiver
2022-07-08T10:55:29.093
<p>I'm working on RF transmitter and receiver modules using two Arduino UNOs. I'm getting an additional noise on the receiver side in serial.println. To be more clear about the question. Hre is my transmitter code</p> <pre><code>// Include RadioHead Amplitude Shift Keying Library #include &lt;RH_ASK.h&gt; // Include dependant SPI Library #include &lt;SPI.h&gt; // Create Amplitude Shift Keying Object RH_ASK rf_driver; void setup() { // Initialize ASK Object rf_driver.init(); Serial.begin(9600); } void loop() { const char *msg = &quot;Hello World&quot;; rf_driver.send((uint8_t *)msg, strlen(msg)); rf_driver.waitPacketSent(); Serial.println((char *)msg); delay(1000); } </code></pre> <p>Here is my receiver code</p> <pre><code>// Include RadioHead Amplitude Shift Keying Library #include &lt;RH_ASK.h&gt; // Include dependant SPI Library #include &lt;SPI.h&gt; // Create Amplitude Shift Keying Object RH_ASK rf_driver; void setup() { // Initialize ASK Object rf_driver.init(); // Setup Serial Monitor Serial.begin(9600); } void loop() { // Set buffer to size of expected message uint8_t buf[11]; uint8_t buflen = sizeof(buf); // Check if received packet is correct size if (rf_driver.recv(buf, &amp;buflen)) { // Message received with valid checksum Serial.print(&quot;Message Received: &quot;); Serial.println((char*)buf); } } </code></pre> <p>And here is my Serial monitor in receiver side <a href="https://i.stack.imgur.com/OJqqf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OJqqf.png" alt="enter image description here" /></a></p> <p>So, can somebody help me to sort out this issue</p>
<p>You're treating a raw buffer as a string.</p> <p>In C a string is an array of characters (11 in your case) terminated by a NULL character. You receive 11 bytes into an 11 byte array and then try and print it - without any terminating character - so the output &quot;overruns&quot; into the memory following your array.</p> <p>You need a buffer of 12 bytes not 11, and you have to make sure that the 12th byte (byte number 11) is zero.</p> <p>Or use <code>Serial.write(buf, buflen);</code> function to write exactly 11 bytes to the serial.</p>
90122
|lcd|library|
How to configure 16x2 character LCD to work with 8bit?
2022-07-08T12:08:53.653
<p>I have the <a href="https://github.com/arduino-libraries/LiquidCrystal" rel="nofollow noreferrer">LiquidCrystal</a> library installed but all the examples are for 4bit connection, I want to drive the LCD with 8bit.</p> <p>In <a href="https://github.com/arduino-libraries/LiquidCrystal/blob/master/src/LiquidCrystal.cpp" rel="nofollow noreferrer">LiquidCrystal.cpp</a> file it says;</p> <blockquote> <p>When the display powers up, it is configured as follows:</p> <p>DL = 1; 8-bit interface data</p> </blockquote> <p>But what's is the function, should it be like this: <code>LiquidCrystal DL(1);</code>? where and how should I call <code>DL = 1;</code>?</p>
<p>You don't &quot;do&quot; anything to enable 8 bit. As it says <em>when the device powers up the DL bit in the configuration is already set, enabling 8 bit</em>.</p> <p>You just need to wire it for 8 bit and specify all 8 bits of wiring in the constructor.</p> <p>The manual entry for the constructor shows you what parameters you can specify:</p> <ul> <li><a href="https://www.arduino.cc/reference/en/libraries/liquidcrystal/liquidcrystal/" rel="nofollow noreferrer">https://www.arduino.cc/reference/en/libraries/liquidcrystal/liquidcrystal/</a></li> </ul>
90136
|atmega328|pins|
Why am I reading only zeroes from PORTB?
2022-07-09T16:46:39.760
<p>I am using a custom Arduino Nano compatible board with an Atmel 328P. I am externally changing the values applied to several pins on PORTB. I expect to be able to read the values of these pins (low or high) but I always read zeroes. However, the pin change interrupt is called. What do I need to do to read values from PORTB?</p> <p>Supply voltage is 5 volts. Pin applied high voltage is 3.3 volts.</p> <p>With the below code, when I change the voltage applied to a pin, LED1 flashes but LED2 does not.</p> <pre><code>#include &lt;avr/interrupt.h&gt; #define LED1_PORT (PORTD) #define LED1_PIN_bm (_BV(4)) //D1, white #define LED2_PORT (PORTD) #define LED2_PIN_bm (_BV(3)) //D2, red volatile bool g_bValueChanged = 0; void setup() { DDRB = 0; //set all as inputs PCMSK0 = 0xfb; //exclude 1 pin because of noise PCICR |= (1 &lt;&lt; PCIE0); //enable pin change interrupt 0 (for pins PB0..7) sei(); } uint8_t g_valuePrevious = 0; void loop() { if (g_bValueChanged) { g_bValueChanged = false; LED1_PORT |= LED1_PIN_bm; delay(40); LED1_PORT &amp;= ~LED1_PIN_bm; delay(40); } uint8_t value = PORTB; if (value != g_valuePrevious) { g_valuePrevious = value; LED2_PORT |= LED2_PIN_bm; delay(40); LED2_PORT &amp;= ~LED2_PIN_bm; delay(40); } } ISR(PCINT0_vect) { g_bValueChanged = true; } </code></pre>
<p>The <code>PORTB</code> register is initialized by the hardware to zero. You never write to this register, so it always stays zero.</p> <p>Maybe you are mixing up <code>PORTB</code> and <code>PINB</code>:</p> <ul> <li><code>PORTB</code> is the port <strong>output</strong> register, controlled by you</li> <li><code>PINB</code> is the port <strong>input</strong> register, for which the bits corresponding to input pins are controlled by whatever drives those pins from the outside.</li> </ul>
90163
|array|char|
pointing to array of chars
2022-07-12T18:44:22.333
<p>I'm trying to pass a list of files (located in sketch) to be read using a library I write. List can have different filenames and vary in number of files.</p> <p>How to pass a this array to my library?</p> <p>for example:</p> <p><code>char *parameterFiles[3] = {&quot;/myIOT_param.json&quot;, &quot;/myIOT2_topics.json&quot;, &quot;/sketch_param.json&quot;};</code></p> <p><strong>EDIT_1</strong></p> <p>To explain more clearly what are my needs: Let's say that my library has a class name <code>myIOT2</code>. That class holds an array that contains a list of all filenames (what shown here is not all class). Those names are different from one use of the library to the other, and it might not have all 4 files ( can be also 0 files stored ).</p> <p>I wish to have the flexibilty not to hard code exact filename in advance, but to pass that array as part of my sketch, as show prior to EDIT_1.</p> <pre><code>class myIOT2 { public: const char *parameter_filenames[4] = {nullptr, nullptr, nullptr, nullptr}; }; </code></pre>
<p>You have to pass both a pointer to the list, and the length of the list as an extra argument. The signature of the function may be something like:</p> <pre class="lang-cpp prettyprint-override"><code>void processFiles(const char *fileList[], int fileCount); </code></pre> <p>Note that <code>const char *fileList[]</code> is just a fancy way of writing <code>const char **fileList</code>. I find the former more readable, but that is completely subjective.</p> <p>Here is a small test code showing this in action:</p> <pre class="lang-cpp prettyprint-override"><code>void processFiles(const char *fileList[], int fileCount) { for (int i = 0; i &lt; fileCount; ++i) { Serial.print(&quot;Processing file &quot;); Serial.println(fileList[i]); } } const char *parameterFiles[3] = { &quot;/myIOT_param.json&quot;, &quot;/myIOT2_topics.json&quot;, &quot;/sketch_param.json&quot; }; void setup() { Serial.begin(9600); processFiles(parameterFiles, 3); } void loop() {} </code></pre> <p>Alternatively, you may put a “sentinel” at the end of the list: a null pointer that signifies that the list ends there:</p> <pre class="lang-cpp prettyprint-override"><code>void processFiles(const char *fileList[]) { for (const char **p = fileList; *p; ++p) { Serial.print(&quot;Processing file &quot;); Serial.println(*p); } } const char *parameterFiles[] = { &quot;/myIOT_param.json&quot;, &quot;/myIOT2_topics.json&quot;, &quot;/sketch_param.json&quot;, nullptr }; void setup() { Serial.begin(9600); processFiles(parameterFiles); } void loop() {} </code></pre> <hr /> <p><strong>Edit</strong>: Answering to EDIT_1.</p> <blockquote> <p>[My library's] class holds an array that contains a list of all filenames</p> </blockquote> <p>First of all, you have to decide who is responsible for storing those file names: the library or its client. When you write:</p> <pre class="lang-cpp prettyprint-override"><code>const char *parameterFiles[3] = { &quot;/myIOT_param.json&quot;, &quot;/myIOT2_topics.json&quot;, &quot;/sketch_param.json&quot; }; </code></pre> <p>you are creating 4 arrays: an array of 3 pointers named <code>parameterFiles</code>, and three arrays of characters holding the file names. Note that those 3 arrays are <em>anonymous</em>: they are not array variables. If the client code tries to pass this <code>parameterFiles</code> to your library, the array identifier will decay to a pointer, and your library will receive that pointer. What should it do with it?</p> <ol> <li><p>The library could just keep a copy of the pointer. The client is then responsible for ensuring that it remains valid for as long as the library may need it. This practically implies that <code>parameterFiles</code> should be a global variable, and should not be modified once given to the library.</p> </li> <li><p>The library could make a copy of the array. Then the client is freed from this responsibility. However, it is still responsible for ensuring that the pointers that were copied from the array remain valid, i.e. that the file names stay in the same place in memory.</p> </li> <li><p>The library could copy the file names themselves. Then the client doesn't have any responsibility about keeping pointers valid.</p> </li> </ol> <p>If you choose option 2 or 3, the library will have to hold one or more arrays. You will then have to choose whether you allocate them statically, or dynamically with <code>new</code>. Dynamic allocation is more efficient when the arrays can vary greatly in length, but it can raise issues of memory fragmentation in RAM-constrained devices.</p> <p>I cannot tell you which option is best: it depends on your use case. In any case, whatever you choose, you should document it: the user of the library should know whether they are responsible for keeping any pointers valid.</p> <p>In the following, I will assume option 2 with static allocation. This is consistent with the code snippets in your question. Also, if the client provides the file names as string literals, then pointers to these strings remain always valid.</p> <p>Here is a toy implementation of the <code>myIOT2</code> class, where the list of file names is copied by the constructor into the class:</p> <pre class="lang-cpp prettyprint-override"><code>class myIOT2 : public Printable { public: static const int maxFileCount = 4; myIOT2(const char *fileList[], int count) { if (count &gt; maxFileCount) count = maxFileCount; // discard extra files fileCount = count; for (int i = 0; i &lt; fileCount; i++) filenames[i] = fileList[i]; } size_t printTo(Print&amp; p) const { size_t count = p.print(F(&quot;myIOT2[&quot;)); for (int i = 0; i &lt; fileCount; i++) { count += p.print('&quot;'); count += p.print(filenames[i]); count += p.print('&quot;'); if (i &lt; fileCount - 1) count += p.print(&quot;, &quot;); } count += p.print(']'); return count; } private: const char *filenames[maxFileCount]; int fileCount; }; </code></pre> <p>Note that, the array of file names being statically allocated, there is a hard maximum on the number of files that can be stored. I made the class <code>Printable</code> only for debugging convenience.</p> <p>And here is an example of this class in use:</p> <pre class="lang-cpp prettyprint-override"><code>const int fileCount = 3; const char *parameterFiles[fileCount] = { &quot;/myIOT_param.json&quot;, &quot;/myIOT2_topics.json&quot;, &quot;/sketch_param.json&quot; }; myIOT2 iot(parameterFiles, fileCount); void setup() { Serial.begin(9600); Serial.println(iot); } void loop() {} </code></pre> <p>This test sketch prints:</p> <pre><code>myIOT2[&quot;/myIOT_param.json&quot;, &quot;/myIOT2_topics.json&quot;, &quot;/sketch_param.json&quot;] </code></pre>
90176
|ino|
What does the .ino file extension mean
2022-07-14T09:30:45.940
<p><strong>What does the <code>.ino</code> file extension mean?</strong></p> <p>We have <code>.cpp</code> meaning C++, <code>.py</code> meaning Python, <code>.exe</code> meaning executable and so-on.They're obvious. The <code>.pde</code> file type that sketches previously used, I think, comes from <em>processing development environment</em> (the arduino IDE being based* on / inspired by <a href="https://processing.org" rel="nofollow noreferrer">processing</a>). But what does <code>.ino</code> mean?</p> <p>There's plenty that explains what such files are, but nothing explains what those three letters mean, if anything.</p> <p><sub>* source <a href="https://en.wikipedia.org/wiki/Arduino" rel="nofollow noreferrer">wikipedia</a></sub></p>
<p>&quot;Arduino&quot; is an Italian word, and &quot;ino&quot; is the suffix which lends itself well to a filename extension.</p> <p>From <a href="https://translate.google.com/?sl=it&amp;tl=en&amp;text=ino%0A%0A1%0ASuffisso%20alterativo%20di%20aggettivi%20e%20sostantivi%3B%20nei%20primi%20ha%20valore%20diminutivo-vezzeggiativo%2C%20talvolta%20con%20sfumatura%20ironica%20(%20biondino%2C%20carino%20)%2C%20oppure%20significa%20appartenenza%20etnica%20(%20alessandrino%2C%20cadorino%20)%2C%20collegamento%20con%20materie%20(%20argentino%2C%20salino%20)%3B%20nei%20secondi%2C%20oltre%20ad%20avere%20valore%20diminutivo-vezzeggiativo%20(%20gattino%2C%20pensierino%20)%2C%20indica%20pure%20un%20mestiere%20(%20ciabattino%2C%20tamburino%20)%2C%20uno%20strumento%20o%20arnese%20o%20apparecchio%20(%20cerino%2C%20lavandino%20)%3B%20in%20alcuni%20casi%20%C3%A8%20applicato%20a%20verbi%20(%20imbianchino%2C%20accendino%20).%0A2%0AIn%20chimica%20organica%2C%20suffisso%20che%20nella%20nomenclatura%20ufficiale%20indica%20gli%20idrocarburi%20acetilenici%2C%20cio%C3%A8%20gli%20alchini%20(%20etino%20).&amp;op=translate" rel="nofollow noreferrer">Google Translate of Italian ino</a>:</p> <blockquote> <p>ino</p> <ol> <li>Suffisso alterativo di aggettivi e sostantivi; nei primi ha valore diminutivo-vezzeggiativo, talvolta con sfumatura ironica ( biondino, carino ), oppure significa appartenenza etnica ( alessandrino, cadorino ), collegamento con materie ( argentino, salino ); nei secondi, oltre ad avere valore diminutivo-vezzeggiativo ( gattino, pensierino ), indica pure un mestiere ( ciabattino, tamburino ), uno strumento o arnese o apparecchio ( cerino, lavandino ); in alcuni casi è applicato a verbi ( imbianchino, accendino ).</li> <li>In chimica organica, suffisso che nella nomenclatura ufficiale indica gli idrocarburi acetilenici, cioè gli alchini ( etino ).</li> </ol> </blockquote> <blockquote> <ol> <li>Alterative suffix of adjectives and nouns; in the former it has a diminutive-pet name, sometimes with an ironic tinge (blond, cute), or it means ethnic affiliation (Alexandrian, Cadore), connection with materials (Argentine, saline); in the latter, in addition to having a diminutive-pet name (kitten, little thought), it also indicates a trade (cobbler, drummer), an instrument or tool or apparatus (match, sink); in some cases it is applied to verbs (painter, lighter).</li> <li>In organic chemistry, suffix that in the official nomenclature indicates acetylenic hydrocarbons, i.e. alkynes (ethin).</li> </ol> </blockquote>
90178
|esp32|tcpip|
SNMP Manager - Multiple IP address -issue
2022-07-14T11:53:51.393
<p>I have multiple SNMP devices on the same network and I am trying to request, <em>via OID numbers</em>, each SNMP device and assign the <strong>response</strong> into an array. When I request a single IP, I get the correct response as expected.</p> <p><strong>Problem:</strong> If I run the same code in a for loop (<em>multiple ip's 192.168.1.150, 192.168.1.151, etc</em>), I get duplicate info. <em>I might be using the wrong callback method, or the SNMP Manager can not dynamically change the ip address..</em> I have researched a lot of topics and tried many avenues, but I can't get past this point.</p> <p><strong>If anyone can assist me, it would help a lot!!</strong></p> <hr /> <p><strong>Example Output:</strong> <em>The model name and serial should be different on each ip</em></p> <pre><code>---------------------- 192.168.8.150 KONICA MINOLTA bizhub C658 A79J021002278 ---------------------- 192.168.8.151 KONICA MINOLTA bizhub C658 A79J021002278 ---------------------- 192.168.8.152 KONICA MINOLTA bizhub C658 A79J021002278 ---------------------- 192.168.8.153 KONICA MINOLTA bizhub C658 A79J021002278 ---------------------- 192.168.8.154 KONICA MINOLTA bizhub C658 A79J021002278 </code></pre> <p><strong>Here is the code</strong></p> <pre><code>#if defined(ESP8266) #include &lt;ESP8266WiFi.h&gt; // ESP8266 Core WiFi Library #else #include &lt;WiFi.h&gt; // ESP32 Core WiFi Library #endif #include &lt;string.h&gt; #include &lt;WiFiUdp.h&gt; #include &lt;Arduino_SNMP_Manager.h&gt; //************************************ //* Your WiFi info * //************************************ const char *ssid = &quot;Workmin_Sales&quot;; const char *password = &quot;workmin92429242&quot;; //************************************ //************************************ //* SNMP Device Info * //************************************ const char *community = &quot;public&quot;; const int snmpVersion = 1; // SNMP Version 1 = 0, SNMP Version 2 = 1 // OIDs const char *oidModelName = &quot;.1.3.6.1.2.1.25.3.2.1.3.1&quot;; // OctetString SysName const char *oidSerialNumber = &quot;.1.3.6.1.2.1.43.5.1.1.17.1&quot;; // OctetString SysName //************************************ //************************************ //* Settings * //************************************ int pollInterval = 20000; // delay in milliseconds //************************************ //************************************ //* Initialise * //************************************ // Variables char *modelNameArray[5]; char *serialNumberArray[5]; char modelName[50]; char *modelNameResponse = modelName; char serialNumber[50]; char *serialNumberResponse = serialNumber; // Blank callback pointer for each OID ValueCallback *callbackSerialNumber; ValueCallback *callbackModelName; //************************************ unsigned long pollStart = 0; // SNMP Objects WiFiUDP udp; // UDP object used to send and receive packets SNMPManager snmp = SNMPManager(community); // Starts an SMMPManager to listen to replies to get-requests SNMPGet snmpRequest = SNMPGet(community, snmpVersion); // Starts an SMMPGet instance to send requests //************************************ //* Function declarations * //************************************ void getSNMP(); //************************************ void setup() { Serial.begin(115200); WiFi.begin(ssid, password); Serial.println(&quot;&quot;); // Wait for connection while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print(&quot;.&quot;); } Serial.println(&quot;&quot;); Serial.print(&quot;Connected to SSID: &quot;); Serial.println(ssid); Serial.print(&quot;IP address: &quot;); Serial.println(WiFi.localIP()); snmp.setUDP(&amp;udp); // give snmp a pointer to the UDP object snmp.begin(); // start the SNMP Manager } void loop() { // put your main code here, to run repeatedly: snmp.loop(); if (millis() - pollStart &gt;= pollInterval) { pollStart += pollInterval; // this prevents drift in the delays getSNMP(); // doSNMPCalculations(); // Do something with the data collected } } void getSNMP() { for (int i = 0; i &lt; 5; i++) { // Build a SNMP get-request add each OID to the request IPAddress router(192, 168, 8, i + 150); // Get callbacks from creating a handler for each of the OID callbackSerialNumber = snmp.addStringHandler(router, oidSerialNumber, &amp;serialNumberResponse); callbackModelName = snmp.addStringHandler(router, oidModelName, &amp;modelNameResponse); snmpRequest.addOIDPointer(callbackSerialNumber); snmpRequest.addOIDPointer(callbackModelName); snmpRequest.setIP(WiFi.localIP()); // IP of the listening MCU // snmpRequest.setPort(501); // Default is UDP port 161 for SNMP. But can be overriden if necessary. snmpRequest.setUDP(&amp;udp); snmpRequest.setRequestID(rand() % 5555); snmpRequest.sendTo(router); snmpRequest.clearOIDList(); delay(1000); modelNameArray[i] = modelNameResponse; serialNumberArray[i] = serialNumberResponse; Serial.print(&quot;192.168.8.&quot;); Serial.println(i + 150); Serial.println(modelNameArray[i]); Serial.println(serialNumberArray[i]); Serial.println(&quot;----------------------&quot;); } } </code></pre>
<p>I think I see multiple issues with the example above.</p> <ol> <li>The <code>snmpRequest.sendTo(router);</code> will send the SNMP packet out. But you need to call <code>snmp.loop()</code> to read the incoming replies to your request. So you need to restructure the code so that you can call loop() potentially many times in order to wait for the incoming replies before you read and store the values.</li> <li><code>serialNumberResponse</code> is a pointer to a character array <code>serialNumber</code> (likewise for the model). If the callback returned serial number <code>123ABC</code> the first time, and the next device was called <code>1XD</code> then the array would have a value of <code>1XDABC</code>. So if you plan to re-use the variable, you'll need to clear it between uses something like: <code>memset(serialNumber, 0, sizeof(serialNumber));</code></li> <li>As you might not always get a successful response, or a response within the time allowed, the value may be still blank, if you're looking to store the values in another variable, you may want to ensure they aren't empty, as this would overwrite the value you may have had back on a previously successful call. If you were dealing with numbers, the value might also be that of a previous call. As pointed out in the answer above, you're dealing with pointers, so if you want to store the value you need to copy the value out, otherwise, you'll just point to the same pointer.</li> </ol> <p>I hope this helps point you in the right direction. I've added an example to the library to show how multiple devices can be queried and the results stored in an array, see: <a href="https://github.com/shortbloke/Arduino_SNMP_Manager/tree/master/examples/ESP_Multiple_SNMP_Device_Polling" rel="nofollow noreferrer">https://github.com/shortbloke/Arduino_SNMP_Manager/tree/master/examples/ESP_Multiple_SNMP_Device_Polling</a>. It stores the responses directly into the array. This might cause values to be cleared in the event of a timeout, I've not tested it completely.</p> <p>Martin</p>
90184
|arduino-uno|
Prevent Resetting of Null Weight when using HX711 with a load cell
2022-07-15T05:47:03.860
<p>Helllo,<br /> I am using the HX711 module and load cell with an arduino uno for force measurements. I am using <a href="https://github.com/olkal/HX711_ADC" rel="nofollow noreferrer">this library</a>.</p> <p>I first use the example <a href="https://github.com/olkal/HX711_ADC/blob/master/examples/Calibration/Calibration.ino" rel="nofollow noreferrer">&quot;Calibration&quot;</a> code for calibration with a 200 g weight. Then I save the calibration constant to the eeprom (choosing yes on the serial monitor). Then the load cell is able to measure weights accurately.</p> <p>After that I remove the weight from the load cell and run <a href="https://github.com/olkal/HX711_ADC/blob/master/examples/Read_1x_load_cell/Read_1x_load_cell.ino" rel="nofollow noreferrer">this code</a> after uncommenting the last line of this part of the above code:</p> <pre><code>LoadCell.begin(); //LoadCell.setReverseOutput(); float calibrationValue; calibrationValue = 696.0; #if defined(ESP8266)|| defined(ESP32) //EEPROM.begin(512); #endif EEPROM.get(calVal_eepromAdress, calibrationValue); // I have uncommented this </code></pre> <p>The weights are measured accurately.</p> <p><strong>But when before powering the arduino, if I keep a weight on the load cell that weight is taken to be 0.</strong></p> <p>For this I have done the following change to the code:</p> <pre><code>boolean _tare = false; </code></pre> <p>But I get the following output on the serial monitor (Note: The following output is obtained on startup when there is/there is no weight on the load cell):</p> <p><a href="https://i.stack.imgur.com/1w7ve.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1w7ve.png" alt="enter image description here" /></a></p> <p><strong>Questions:</strong> What is the use of the following line:</p> <pre><code>calibrationValue = 696.0; // uncomment this if you want to set the calibration value in the sketch </code></pre> <p>Is it useless for the code I am using above? Because I am using the calibration value from the eeprom.</p> <p>Q2) Why is it showing -39000 as an output value? And how to correct it?</p> <p><strong>Alternate Statement:</strong> In other words, I want to use the HX711 module with the arduino and a load cell. I will first calibrate it with a known weight and save the calibration value. Before powering up the arduino I will keep a weight on the load cell. After powering up the weight value should be the absolute value instead of making the Weight Null.</p> <p><strong>EDIT1:</strong> I incorporate the changes suggested in the answers by @Edgar Bonet and also make the problem more clear just in case. According to suggestions I have made the corresponding changes to the calibration code. Then I run that and the values are saved to eeprom. Code changes:</p> <pre><code>const int calVal_eepromAdress = 0; const int tare_eepromAdress = sizeof(float); </code></pre> <p>and</p> <pre><code>#endif EEPROM.put(calVal_eepromAdress, newCalibrationValue); EEPROM.put(tare_eepromAdress, LoadCell.getTareOffset()); #if defined(ESP8266)|| defined(ESP32) EEPROM.commit(); </code></pre> <p>Now, I wish to run the <a href="https://github.com/olkal/HX711_ADC/blob/master/examples/Read_1x_load_cell/Read_1x_load_cell.ino" rel="nofollow noreferrer">second script</a> and for this to display the correct weights. This should work in all cases regardless of whether a weight has not been kept on the load cell or has been kept and should be independent of the weight that has been kept. To this script I have made the following changes:</p> <pre><code>const int calVal_eepromAdress = 0; const int tare_eepromAdress = sizeof(float); </code></pre> <p>and</p> <pre><code>// Inside void setup() void setup() { Serial.begin(57600); delay(10); Serial.println(); Serial.println(&quot;Starting...&quot;); LoadCell.begin(); //LoadCell.setReverseOutput(); //uncomment to turn a negative output value to positive float calibrationValue; // calibration value (see example file &quot;Calibration.ino&quot;) float tareValue; calibrationValue = 696.0; // uncomment this if you want to set the calibration value in the sketch tareValue = 0; #if defined(ESP8266)|| defined(ESP32) //EEPROM.begin(512); // uncomment this if you use ESP8266/ESP32 and want to fetch the calibration value from eeprom #endif EEPROM.get(calVal_eepromAdress, calibrationValue); // uncomment this if you want to fetch the calibration value from eeprom EEPROM.get(tare_eepromAdress, tareValue); unsigned long stabilizingtime = 2000; // preciscion right after power-up can be improved by adding a few seconds of stabilizing time boolean _tare = true; //set this to false if you don't want tare to be performed in the next step LoadCell.start(stabilizingtime, _tare); if (LoadCell.getTareTimeoutFlag()) { Serial.println(&quot;Timeout, check MCU&gt;HX711 wiring and pin designations&quot;); while (1); } else { LoadCell.setCalFactor(calibrationValue); // set calibration value (float) LoadCell.setTareOffset(tareValue); Serial.println(&quot;Startup is complete&quot;); } } </code></pre> <p><strong>EDIT2:</strong></p> <pre><code>#if defined(ESP8266)|| defined(ESP32) EEPROM.begin(512); #endif EEPROM.put(calVal_eepromAdress, newCalibrationValue); EEPROM.put(tare_eepromAdress, LoadCell.getTareOffset()); Serial.println(newCalibrationValue); Serial.println(LoadCell.getTareOffset()); </code></pre> <p>Output:</p> <pre><code>-206.90 8368790 </code></pre> <p>In the second script:</p> <pre><code>#if defined(ESP8266)|| defined(ESP32) //EEPROM.begin(512); // uncomment this if you use ESP8266/ESP32 and want to fetch the calibration value from eeprom #endif EEPROM.get(calVal_eepromAdress, calibrationValue); // uncomment this if you want to fetch the calibration value from eeprom EEPROM.get(tare_eepromAdress, tareValue); Serial.println(calibrationValue); Serial.println(tareValue); </code></pre> <p>Output:</p> <pre><code>-206.90 0.00 </code></pre> <p>I am uploading my codes onto Github just in case. They can be found <a href="https://github.com/atharvaaalok/LoadCell_Corrected" rel="nofollow noreferrer">here</a>.</p> <p>Q) What is happening here?</p> <p><strong>EDIT3:</strong> The following changes make it work like a charm: In the &quot;Calibration&quot; script:</p> <pre><code>long tareValue = LoadCell.getTareOffset(); // Instead of float tareValue </code></pre> <p>Similarly in the second script:</p> <pre><code>long tareValue; // Instead of float tareValue </code></pre>
<p>In order to convert the raw ADC readings to a weight, the library needs two coefficients:</p> <ul> <li>a “tare offset”, which is the raw reading when there is no weight on the scale</li> <li>a gain, or “calibration factor”, which is the ratio of a change in the ADC reading to the corresponding change in weight.</li> </ul> <p>The examples provided with the library use the EPPROM to store and retrieve the calibration factor, but not the tare offset. This makes sense as, in common usage, a weight scale is always zeroed at power up, or right after power up. This is usually desirable as one would often place an empty container on the scale which should not affect the displayed weight.</p> <p>If you do not want to zero the scale at power-up, then you need your sketch to remember the tare offset in addition to the calibration factor. For this, you can use the methods of <code>LoadCell</code>:</p> <pre class="lang-cpp prettyprint-override"><code>// Get the tare offset (raw data value output without // the scale &quot;calFactor&quot;). long getTareOffset(); // Set new tare offset (raw data value input without // the scale &quot;calFactor&quot;). void setTareOffset(long newoffset); </code></pre> <p>Now, to the more specific questions:</p> <blockquote> <p>What is the use of the following line:</p> <pre class="lang-cpp prettyprint-override"><code>calibrationValue = 696.0; </code></pre> </blockquote> <p>None. It is just an example. You are supposed to either replace this number with your measured calibration factor, or remove this line and read <code>calibrationValue</code> from the EEPROM.</p> <blockquote> <p>Why is it showing -39000 as an output value?</p> </blockquote> <p>Because the tare offset has not been set, so it presumably defaults to zero.</p> <hr /> <p><strong>Edit</strong>: Answering extra questions in comment.</p> <blockquote> <p>Do I need to store this value to the eeprom when running the calibration script?</p> </blockquote> <p>You can store it whenever it is convenient to you. The calibration script seems a good place.</p> <blockquote> <p>I am not able to get this into code. I read the source files but I am unsure about what changes to make.</p> </blockquote> <p>What you may try (untested):</p> <ol> <li><p>right after the line</p> <pre class="lang-cpp prettyprint-override"><code>const int calVal_eepromAdress = 0; </code></pre> <p>add this:</p> <pre class="lang-cpp prettyprint-override"><code>const int tare_eepromAdress = sizeof(float); </code></pre> </li> <li><p>Right after this:</p> <pre class="lang-cpp prettyprint-override"><code>EEPROM.put(calVal_eepromAdress, newCalibrationValue); </code></pre> <p>add this:</p> <pre class="lang-cpp prettyprint-override"><code>EEPROM.put(tare_eepromAdress, LoadCell.getTareOffset()); </code></pre> </li> </ol>
90187
|arduino-uno|arduino-nano|communication|
Is there a way to connect two Arduinos, when one of them has all of its pins occupied?
2022-07-15T18:49:07.280
<p>I want to connect an Arduino Uno to an Arduino Nano, so that it can send signals. The problem is that the Arduino Uno has a motor shield connected to it, and it takes up all pins of the Arduino.</p> <p>This is a picture of the whole motor shield contraption if it helps:</p> <p><a href="https://i.stack.imgur.com/UAv4k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UAv4k.png" alt="enter image description here" /></a></p> <p>Does anybody know any solution for this?</p>
<p>Pins 0 and 1 are serial pins which are also connected to usb, and you use them when you are programming your board or when you send anything to serial. It is unlikely that any shield uses it unless it has to and it although has a benefit of being able to listen to what the Arduino sends. I think hitching a ride on pins 1 and 0 (rx/tx) would be the easiest. SO you can print or write to them the same way as you respond to yourself.</p> <p>Just a warning that when you are sending data between two boards and Print numbers they come as symbols of the numbers, not the numbers themselves So <code>Serial.print(7)</code> would arrive to the next arduino as number 55 or symbol '7'. If you are sending numbers between two arduinos you can use write <code>Serial.write(7);</code> which does not change data, but your serial monitor on a computer wont read it right, or you can send them as symbols, but then the arduino listening may have to convert number symbol to the number. (sooner or later you will have to create yourself a simple function to convert symbols to numbers in your project...</p>
90195
|uart|hex|
Send HEX number over serial
2022-07-16T17:29:58.400
<p>I have a RS232 device that I am able to communicate with using RealTerm on a windows PC.</p> <p>The device is expecting a hex string like <code>AA BB 03 01 03 EE</code></p> <p><a href="https://i.stack.imgur.com/NHILF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NHILF.jpg" alt="enter image description here" /></a></p> <hr /> <p>How would I send the equivalent string from an arduino? (I feel confident the arduino is wired correctly since I can see incoming uart data)</p> <p>Things I have tried</p> <pre><code>void setup() { Serial.begin(9600); // opens serial port, sets data rate to 9600 bps } void loop() { Serial.println('AA BB 03 01 01 EE', &quot;OCT&quot;); delay(3000); Serial.println('0xAA 0xBB 0x03 0x01 0x01 0xEE', &quot;DEC&quot;); delay(3000); Serial.println('AA BB 03 01 01 EE', &quot;DEC&quot;); delay(3000); Serial.println('AA BB 03 01 01 EE', &quot;DEC&quot;); delay(3000); Serial.println('AA BB 03 01 01 EE', &quot;DEC&quot;); delay(3000); Serial.print('0xAA 0xBB 0x03 0x01 0x01 0xEE', &quot;DEC&quot;); delay(3000); Serial.print('AA BB 03 01 01 EE', &quot;DEC&quot;); delay(3000); Serial.print('AA BB 03 01 01 EE', &quot;DEC&quot;); delay(3000); Serial.print('AA BB 03 01 01 EE', &quot;DEC&quot;); delay(3000); Serial.println('AA BB 03 01 01 EE', HEX); delay(3000); Serial.println('0xAA 0xBB 0x03 0x01 0x01 0xEE', HEX); delay(3000); Serial.println('0xAA 0xBB 0x03 0x01 0x01 0xEE'); delay(3000); Serial.println('0xAA 0xBB 0x03 0x01 0x01 0xEE', HEX); delay(3000); Serial.write('AA BB 03 01 01 EE'); delay(3000); Serial.write('0xAA 0xBB 0x03 0x01 0x01 0xEE'); delay(3000); } </code></pre> <p>I've also tried using double quotes as mentioned in the comments</p> <pre><code> Serial.write(&quot;AA BB 03 01 01 EE&quot;); delay(3000); Serial.write(&quot;0xAA 0xBB 0x03 0x01 0x01 0xEE&quot;); delay(3000); Serial.write(&quot;101010101011101100000011000000010000000111101110&quot;); delay(2000); </code></pre> <p>Additionally I've tried writing the serial one line at a time</p> <pre><code> Serial.write(0xaa); // AA Serial.write(0xbb); // BB Serial.write(0x03); // 03 Serial.write(0x01); // 01 Serial.write(0x01); // 01 Serial.write(0xee); // EE Serial.write(0x0d); // \r Serial.write(0x0a); // \n delay(3000); </code></pre> <p>Additional Information</p> <ul> <li><a href="https://www.youtube.com/watch?v=bQ7qvjxSUXU" rel="nofollow noreferrer">controlling projector using arduino</a></li> <li><a href="https://www.reddit.com/r/Esphome/comments/i8srtv/projector_control/?sort=confidence" rel="nofollow noreferrer">Adding \r\n to hex sent over arduino</a></li> </ul>
<p>if device expects actual numbers, then it does not receive them in hex format or decimal, but in binary. in which case you would need an array of numbers and then go with them using for loop (or purpouse made function.</p> <pre><code>byte sequence[]={0xAA, 0xBB, 0x03, 0x01, 0x01, 0xEE}; for(byte i=0; i&lt;sizeof(sequence);i++) Serial.write(sequence[i]); </code></pre> <p>if you have to send it as a HEX, then its most likely a case of hex representation and you can use printf for that</p> <pre><code>Serial.printf(&quot;0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X&quot;, 0xAA, 0xBB, 0x03, 0x01, 0x01, 0xEE); </code></pre> <p>Another think is that you should be careful using <code>println</code> when communicating with other devices. <code>println</code> ads extra character (number) for new line, after the data you wish to send. if you only want to send data you wish to send, then use <code>print</code> instead</p> <p>Edit: Thanks for the note from Edgar Bonet, I was warned that printf is still not a standard instruction outside of the ESP core. Its well worth adding it up by yourself. Look for a guide on arduino playground.</p>
90204
|esp8266|spiffs|littlefs|
How to store a struct in a file?
2022-07-17T18:47:16.257
<p>I'm trying to store (read&amp;write( a struct using <code>LittleFS</code> on ESP8266.</p> <p>Appreciate assistance</p> <pre><code>struct oper_string { bool state; /* On or Off */ uint8_t step; /* Step, in case of PWM */ uint8_t reason; /* What triggered the button */ time_t ontime; /* Start Clk */ time_t offtime; /* Off Clk */ }; </code></pre>
<p>one can write a struct directly into a SPIFS/ FFAT file like this:</p> <pre><code> * EXAMPLE READING AND WRITING A C++ STRUCT TO A FILE */ #include &lt;FS.h&gt; #include &lt;SPIFFS.h&gt; typedef struct { char someString[10]; float someFloat; } MyStruct; MyStruct myStruct = { &quot;test test&quot;,1.7 }; void setup() { // put your setup code here, to run once: Serial.begin(115200); if(!SPIFFS.begin()){ Serial.println(&quot;Card Mount Failed&quot;); return; } strncpy( myStruct.someString, &quot;testtesttest&quot;, sizeof(myStruct.someString) ); File myFile = SPIFFS.open(&quot;/somefile.txt&quot;, FILE_WRITE); myFile.write((byte *)&amp;myStruct, sizeof(myStruct)); myFile.close(); } void loop() { // put your main code here, to run repeatedly: File myFile = SPIFFS.open(&quot;/somefile.txt&quot;, FILE_WRITE); myFile.read((byte *)&amp;myStruct, sizeof(myStruct)); myFile.close(); Serial.printf( &quot;read: %s, %.2f\n&quot;, myStruct.someString, myStruct.someFloat ); delay(1000); } </code></pre> <p>the code above is available on <a href="https://gist.github.com/CelliesProjects/7fab9013517583b3a0922c0f153606a1" rel="nofollow noreferrer">this</a> Github Gist.</p>
90222
|serial|arduino-mega|terminal|
Arduino Serial to USB=>serial data issue
2022-07-19T19:58:46.543
<p>I am using Mega 2560 to receive serial data from another device but the data appears on the serial terminal are strange characters. then i connected my USB to serial cable (HL-340) to the device and tried in serial terminal(Termite), data is landing fine. Replaced Arduino with another one since I believed there could be a problem, but the problem persisted. for further investigation i have connected my Arduino (Mega-2560) to my serial(USB-&gt;Serial) cable directly to receive data on the terminal but strangely even this is showing the wrong data (Arduino terminal is displaying the wright data but the data appears on the other terminal is wrong) sendind &quot;c&quot; receiving &quot;N&quot;... what could be the reason for this..its a simple code to print character on the screen. Thx</p> <p><a href="https://i.stack.imgur.com/oXKzD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oXKzD.jpg" alt="HL-340 USB-Serial cable" /></a> <a href="https://i.stack.imgur.com/Xioio.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xioio.jpg" alt="Arduino Mega-2560" /></a> <a href="https://i.stack.imgur.com/sN5Yr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sN5Yr.png" alt="Code and Terminal's data" /></a></p>
<p>You need to be careful. Normal devices that have a &quot;Serial&quot; interface actually have an RS232 interface. While the data transmission scheme is similar with the &quot;Serial&quot; interface on the Uno/Mega (UART on TTL logic), RS232 has totally different voltage levels (up to -15 to +15V), which can kill your Arduino.</p> <p>To connect an RS232 device to an Arduino you need a level converter (to convert between the RS232 levels and the TTL (Transistor Transistor Logic) level of the Arduino. The chip MAX232 is typically used for this. There are many resources about that on the web and even ready to use modules, which are equipped with a MAX232 and a RS232/Serial plug.</p>
90233
|arduino-uno|mpu6050|gyroscope|imu|
Gyro reading of MPU6050 drifts too much on fast changes only
2022-07-20T11:17:27.767
<p>I am trying to write a simple sketch for the MPU6050.</p> <p>The problem is that the sensor is pretty much solid when stationary or changing the angle steadily at slow to mid angular velocities but if I try to change the angle too fast there's a huge drift in the readings by pretty much tens of degrees in either direction as shown in the below images from the serial plotter.</p> <p>On slow to mid changes in the pitch angle the gyro is tracking the accelerometer pitch almost identically (it drifts a little over time but it's normal and acceptable for the complementary filter).</p> <p>On fast changes however the pitch drifts instantly by tens of degrees from the accelerometer. The huge drift makes the complementary filter pretty much useless in correcting the output</p> <p>It's my first try with the sensor so I don't have any experience with its parameters. But the problem seems to be in the lines of integrating the new angular velocities in roll and pitch.</p> <ul> <li><p>I got lazy and used the default sensitivity scale factors; does this have anything to do with this behaviour?</p> </li> <li><p>The dt measured for the Arduino is 20 ms between readings; is this too slow for the fast changes or something?</p> </li> <li><p>The datasheet also mentioned a programmable output range. Does this need to be programmed for more bandwidth and accurate results?</p> </li> </ul> <h2>EDIT:</h2> <p>I tried to read a bit about the sensitivity scale factor. It seemed that increasing the angular velocity beyond 250 degrees per second is not measured when selecting the default configuration.</p> <p>After some testing I realized that 1000 deg/s is a good configuration for me; the drift certainly is much better but still not what I hoped for. It still drifts by +- 10 degrees in two or three seconds of moving it around.</p> <h2>Slow to Mid changes output:</h2> <p><a href="https://i.stack.imgur.com/qbPlS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qbPlS.png" alt="Slow to Mid speed changes in the pitch" /></a></p> <h2>Fast changes output:</h2> <p><a href="https://i.stack.imgur.com/OBhg7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OBhg7.png" alt="Fast changes in the pitch" /></a></p> <pre><code>#include &lt;Wire.h&gt; #define CAL_AVERAGE 2000 const int MPU = 0x68; //I2C address of MPU6050 const float alpha = 0.95; double ax, ay, az; double gx, gy, gz; //float accAngleX, accAngleY, accAngleZ; //float gyroAgnleX, gyroAngleY, gyroAngleZ; double accErrorX, accErrorY, accErrorZ; double gyroErrorx, gyroErrorY, gyroErrorZ; double accRoll, accPitch; double gyroRoll, gyroPitch, gyroYaw; double roll, pitch, yaw; double dt, currentTime, previousTime; void setup(){ previousTime = 0; Serial.begin(115200); Wire.begin(); //init the communication //reset the mpu Wire.beginTransmission(MPU); Wire.write(0x6B); Wire.write(0x00); Wire.endTransmission(true); //calibrate here calculateError(); } void loop(){ readAcc(); readGyro(); //get roll and pitch of accelerometer accRoll = atan2(ay, az) * 180 / PI; accPitch = atan2(ax, az) * 180 / PI; currentTime = millis(); //set gyro roll and pitch for accelerometer roll and pitch on first reading only if (previousTime != 0) { //get roll, pitch and yaw of gyro dt = currentTime - previousTime; dt /= 1000; gyroRoll += gx * dt; gyroPitch += -gy * dt; gyroYaw += gz * dt; } else { gyroRoll = accRoll; gyroPitch = accPitch; gyroYaw = 0; } previousTime = currentTime; roll = alpha*gyroRoll + (1 - alpha)*accRoll; pitch = alpha*gyroPitch + (1 - alpha)*accPitch; yaw = gyroYaw; //finally print the values collected printData(); } void readAcc(){ //first read accelerometer data Wire.beginTransmission(MPU); Wire.write(0x3B); Wire.endTransmission(false); Wire.requestFrom(MPU, 6, true); //accelerometer raw data ax = ( (Wire.read() &lt;&lt; 8) | Wire.read() ) / 16384.0; ay = ( (Wire.read() &lt;&lt; 8) | Wire.read() ) / 16384.0; az = ( (Wire.read() &lt;&lt; 8) | Wire.read() ) / 16384.0; ax -= accErrorX; ay -= accErrorY; az -= accErrorZ; } void readGyro(){ //second read gyro Wire.beginTransmission(MPU); Wire.write(0x43); Wire.endTransmission(false); Wire.requestFrom(MPU, 6, true); //gyro raw data gx = ( (Wire.read() &lt;&lt; 8) | Wire.read() ) / 131.0; gy = ( (Wire.read() &lt;&lt; 8) | Wire.read() ) / 131.0; gz = ( (Wire.read() &lt;&lt; 8) | Wire.read() ) / 131.0; gx -= gyroErrorx; gy -= gyroErrorY; gz -= gyroErrorZ; } void calculateError(){ float axErr = 0, ayErr = 0, azErr = 0; float gxErr = 0, gyErr = 0, gzErr = 0; for (int i = 0; i &lt; CAL_AVERAGE; i++) { readAcc(); az = az - 1; axErr += ax; ayErr += ay; azErr += az; readGyro(); gxErr += gx; gyErr += gy; gzErr += gz; } accErrorX = axErr/CAL_AVERAGE; accErrorY = ayErr/CAL_AVERAGE; accErrorZ = azErr/CAL_AVERAGE; gyroErrorx = gxErr/CAL_AVERAGE; gyroErrorY = gyErr/CAL_AVERAGE; gyroErrorZ = gzErr/CAL_AVERAGE; } void printData() { Serial.print(ax); Serial.print(&quot;, &quot;); Serial.print(ay); Serial.print(&quot;, &quot;); Serial.print(az); Serial.print(&quot;, &quot;); Serial.print(gx); Serial.print(&quot;, &quot;); Serial.print(gy); Serial.print(&quot;, &quot;); Serial.print(gz); Serial.print(&quot;, &quot;); Serial.print(accPitch); Serial.print(&quot;, &quot;); Serial.print(accRoll); Serial.print(&quot;, &quot;); Serial.print(gyroPitch); Serial.print(&quot;, &quot;); Serial.print(gyroRoll); Serial.print(&quot;, &quot;); Serial.print(gyroYaw); Serial.print(&quot;, &quot;); Serial.print(pitch); Serial.print(&quot;, &quot;); Serial.print(roll); Serial.print(&quot;, &quot;); Serial.print(yaw); Serial.print(&quot;, &quot;); Serial.println(dt); } </code></pre>
<p>In his answer, st2000 recommends you use quaternions, rather than Euler angles, for tracking the orientation of your vehicle. I will give the exact same recommendation, but for a different reason: the formulas you use, namely</p> <pre class="lang-cpp prettyprint-override"><code>gyroRoll += gx * dt; gyroPitch += -gy * dt; gyroYaw += gz * dt; </code></pre> <p>are just plain wrong. They are correct if rotations only ever happen along a single axis. They are also “kinda good” (correct as a first-order approximation) if the angles involved are very small. But in the general case, they are wrong. A easy way to convince yourself of this fact is to notice that the final (yaw, pitch, roll) being the sum of many small contributions, they do not depend on the <em>order</em> in which these contributions were added. In other words, these formulas imply that the composition of rotations is commutative, which I hope you know is not the case.</p> <p>The only reasonable ways of composing many rotations (which is what this attitude-tracking code tries to do) are rotation matrices and quaternions, the latter being more efficient.</p> <p>Now, a few remarks:</p> <ol> <li><p>You should not track (<code>gyroRoll</code>, <code>gyroPitch</code> and <code>gyroYaw</code>) independently from (<code>roll</code>, <code>pitch</code>, <code>yaw</code>), otherwise your complementary filter becomes inefficient at canceling gyro drift. You should instead merge those variable into a single triplet.</p> </li> <li><p>The line</p> <pre class="lang-cpp prettyprint-override"><code>( (Wire.read() &lt;&lt; 8) | Wire.read() ) / 16384.0; </code></pre> <p>gets you the two bytes from the MPU in an unspecified order. They may be in the right order with this particular version of this particular compiler when run with this particular set of options, but you should not count on this order being reliable. You should instead read the two bytes in two separate statements.</p> </li> <li><p>If you do not care about the yaw, you may just track the gravity vector instead of the full attitude. This should save you the calls to <code>atan2()</code> and possibly simplify the math further. You may not even need the quaternions after all.</p> </li> </ol>
90235
|arduino-mega|uploading|avrdude|atmega2560|
Avrdude verification error when uploading to Arduino Mega 2560
2022-07-20T14:04:51.873
<p>I have been getting the error</p> <pre><code>avrdude: verification error, first mismatch at byte 0x036c 0xb8 != 0xf8 avrdude: verification error; content mismatch avrdude done. Thank you. </code></pre> <p>When trying to upload the example blink sketch to an Arduino mega 2560.</p> <p>I did some googling and found that the common recommendation to solve this is to flash the bootloader.</p> <p>Which does fix the issue for the first upload after flashing, but the issue reappears after one upload. But every time I flash the bootloader I do get one successful upload following that with no errors.</p> <p>The mismatch is always at 0x036c every time.</p>
<p>The verification is there to check two possible error situations: Transmission error while uploading or faulty flash memory. Apparently, the error can also happen for a bunch of other reasons (see the linked answer), but these two cases should still be considered. Since another Arduino works with the same cable, it's unlikely a communication error and hence, based on all we know, I am assuming your Arduino is bad.</p> <p>You might be lucky that for some reason (the fault is in some piece of code that's not actually used) the program works despite the error, but it's likely that sooner or later you'll get very strange crashes or otherwise undefined behavior.</p>
90244
|esp8266|nodemcu|stepper-motor|esp8266webserver|
ESP8266 web server not responding when running a http request function
2022-07-20T22:24:59.320
<p>I am trying to build something that can control a stepper motor based on weather information from openweathermap. I've set up a ESP8266 webserver to manually control motor movement with buttons and I have set up the structure to talk to openweathermap API to get the information I want (printing them to serial monitor for now for testing).</p> <p>However, when I combined the 2 things break. The current code allows me to get weather perfectly but I can no longer connect to my web server running in STA mode. Something in the <code>getWeather()</code> function is messing with the web server because if I remove <code>getWeather()</code> from my loop the web server works.</p> <p>Any idea what I am doing wrong here?</p> <pre><code>#include &lt;SPI.h&gt; #include &lt;AccelStepper.h&gt; #include &lt;ESP8266WiFi.h&gt; #include &lt;ESP8266WebServer.h&gt; #include &lt;ESP8266HTTPClient.h&gt; // http web access library #include &lt;ArduinoJson.h&gt; // JSON decoding library // Define stepper motor connections and motor interface type. Motor interface type must be set to 1 when using a driver: #define dirPin 5 #define stepPin 4 #define motorInterfaceType 1 bool motorStop; bool motorCW; bool motorCCW; AccelStepper stepper = AccelStepper(motorInterfaceType, stepPin, dirPin); //Put your SSID &amp; Password const char* ssid = &quot;[ssid]&quot;; // Enter SSID here const char* password = &quot;[password]&quot;; //Enter Password here //OpenWeatherMap API key String apiKey= &quot;[apikey]&quot;; //OpenWeatherMap location String location= &quot;lat=37.30&amp;lon=-121.91&quot;; String unit= &quot;metric&quot;; const unsigned long postingInterval = 1000*60*60; // delay between updates, in milliseconds WiFiClient client; ESP8266WebServer server(80); // Set your Static IP address IPAddress local_IP(192, 168, 86, 248); // Set your Gateway IP address IPAddress gateway(192, 168, 86, 1); IPAddress subnet(255, 255, 255, 0); IPAddress primaryDNS(192, 168, 86, 1); void setup() { Serial.begin(9600); delay(100); // Configures static IP address if (!WiFi.config(local_IP, gateway, subnet,primaryDNS)) { Serial.println(&quot;STA Failed to configure&quot;); } stepper.setMaxSpeed(1000); Serial.println(&quot;Connecting to &quot;); Serial.println(ssid); //connect to your local wi-fi network WiFi.begin(ssid, password); //check wi-fi is connected to wi-fi network while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.print(&quot;.&quot;); } //Print out connection info Serial.println(&quot;&quot;); Serial.println(&quot;WiFi connected..!&quot;); server.on(&quot;/&quot;, handle_OnConnect); server.on(&quot;/cw_on&quot;, handle_CW_on); server.on(&quot;/cw_off&quot;, handle_CW_off); server.on(&quot;/ccw_on&quot;, handle_CCW_on); server.on(&quot;/ccw_off&quot;, handle_CCW_off); server.on(&quot;/mstop&quot;, handle_stop); server.onNotFound(handle_NotFound); server.begin(); Serial.println(&quot;HTTP server started&quot;); } void loop() { server.handleClient(); if(motorStop) {stepper.setSpeed(0);} if(motorCW) {stepper.setSpeed(400);} if(motorCCW) {stepper.setSpeed(-400);} // Step the motor with a constant speed as set by setSpeed(): stepper.runSpeed(); getWeather(); } void getWeather() { // if there's a successful connection: if (client.connect(&quot;api.openweathermap.org&quot;, 80)) { Serial.println(&quot;connected&quot;); // send the HTTP PUT request: client.println(&quot;GET /data/2.5/onecall?&quot; + location + &quot;&amp;exclude=current,minutely,hourly&quot; + &quot;&amp;appid=&quot; + apiKey); client.println(&quot;Host: api.openweathermap.org&quot;); client.println(&quot;Connection: close&quot;); client.println(); const size_t capacity = 8*JSON_ARRAY_SIZE(1) + JSON_ARRAY_SIZE(8) + 16*JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + 8*JSON_OBJECT_SIZE(6) + 8*JSON_OBJECT_SIZE(14) + 1810; DynamicJsonDocument doc(capacity); deserializeJson(doc, client); float lat = doc[&quot;lat&quot;]; // 37.3 float lon = doc[&quot;lon&quot;]; // -121.91 const char* timezone = doc[&quot;timezone&quot;]; // &quot;America/Los_Angeles&quot; int timezone_offset = doc[&quot;timezone_offset&quot;]; // -25200 JsonArray daily = doc[&quot;daily&quot;]; // tomorrow's forecast (daily_1) JsonObject daily_1 = daily[1]; long daily_1_dt = daily_1[&quot;dt&quot;]; // 1596225600 long daily_1_sunrise = daily_1[&quot;sunrise&quot;]; // 1596201109 long daily_1_sunset = daily_1[&quot;sunset&quot;]; // 1596251761 JsonObject daily_1_temp = daily_1[&quot;temp&quot;]; float daily_1_temp_day = daily_1_temp[&quot;day&quot;]; // 306.61 float daily_1_temp_min = daily_1_temp[&quot;min&quot;]; // 288.67 float daily_1_temp_max = daily_1_temp[&quot;max&quot;]; // 306.61 float daily_1_temp_night = daily_1_temp[&quot;night&quot;]; // 288.67 float daily_1_temp_eve = daily_1_temp[&quot;eve&quot;]; // 295.94 float daily_1_temp_morn = daily_1_temp[&quot;morn&quot;]; // 293.26 JsonObject daily_1_feels_like = daily_1[&quot;feels_like&quot;]; int daily_1_feels_like_day = daily_1_feels_like[&quot;day&quot;]; // 303.31 float daily_1_feels_like_night = daily_1_feels_like[&quot;night&quot;]; // 287.59 float daily_1_feels_like_eve = daily_1_feels_like[&quot;eve&quot;]; // 293.77 float daily_1_feels_like_morn = daily_1_feels_like[&quot;morn&quot;]; // 292.42 int daily_1_pressure = daily_1[&quot;pressure&quot;]; // 1015 int daily_1_humidity = daily_1[&quot;humidity&quot;]; // 17 float daily_1_dew_point = daily_1[&quot;dew_point&quot;]; // 278.68 float daily_1_wind_speed = daily_1[&quot;wind_speed&quot;]; // 3.12 int daily_1_wind_deg = daily_1[&quot;wind_deg&quot;]; // 318 JsonObject daily_1_weather_0 = daily_1[&quot;weather&quot;][0]; int daily_1_weather_0_id = daily_1_weather_0[&quot;id&quot;]; // 800 const char* daily_1_weather_0_main = daily_1_weather_0[&quot;main&quot;]; // &quot;Clear&quot; const char* daily_1_weather_0_description = daily_1_weather_0[&quot;description&quot;]; // &quot;clear sky&quot; const char* daily_1_weather_0_icon = daily_1_weather_0[&quot;icon&quot;]; // &quot;01d&quot; int daily_1_clouds = daily_1[&quot;clouds&quot;]; // 0 int daily_1_pop = daily_1[&quot;pop&quot;]; // 0 float daily_1_uvi = daily_1[&quot;uvi&quot;]; // 9.53 // print out weather information Serial.print(&quot;Tomorrow's Forecast&quot;); Serial.print(&quot;Temperature: &quot;); Serial.println(daily_1_feels_like_day); Serial.print(&quot;Weather: &quot;); Serial.println(daily_1_weather_0_main); delay (postingInterval); } else { // if you couldn't make a connection: Serial.println(&quot;connection failed&quot;); delay (postingInterval); } } void handle_OnConnect() { motorStop = HIGH; motorCW = LOW; motorCCW = LOW; Serial.println(&quot;Motor: Stopped&quot;); server.send(200, &quot;text/html&quot;, SendHTML(motorStop, motorCW, motorCCW)); } void handle_CW_on() { motorStop = LOW; motorCW = HIGH; motorCCW = LOW; Serial.println(&quot;Motor: Running Clock-wise&quot;); server.send(200, &quot;text/html&quot;, SendHTML(motorStop, motorCW, motorCCW)); } void handle_CW_off() { motorStop = HIGH; motorCW = LOW; motorCCW = LOW; Serial.println(&quot;Motor: Stopped&quot;); server.send(200, &quot;text/html&quot;, SendHTML(motorStop, motorCW, motorCCW)); } void handle_CCW_on() { motorStop = LOW; motorCW = LOW; motorCCW = HIGH; Serial.println(&quot;Motor: Motor: Running Counter Clock-wise&quot;); server.send(200, &quot;text/html&quot;, SendHTML(motorStop, motorCW, motorCCW)); } void handle_CCW_off() { motorStop = HIGH; motorCW = LOW; motorCCW = LOW; Serial.println(&quot;Motor: Stopped&quot;); server.send(200, &quot;text/html&quot;, SendHTML(motorStop, motorCW, motorCCW)); } void handle_stop() { motorStop = HIGH; motorCW = LOW; motorCCW = LOW; Serial.println(&quot;Motor: Stopped&quot;); server.send(200, &quot;text/html&quot;, SendHTML(motorStop, motorCW, motorCCW)); } void handle_NotFound(){ server.send(404, &quot;text/plain&quot;, &quot;Not found&quot;); } String SendHTML(uint8_t mstop,uint8_t cw, uint8_t ccw){ String ptr = &quot;&lt;!DOCTYPE html&gt; &lt;html&gt;\n&quot;; ptr +=&quot;&lt;head&gt;&lt;meta name=\&quot;viewport\&quot; content=\&quot;width=device-width, initial-scale=1.0, user-scalable=no\&quot;&gt;\n&quot;; ptr +=&quot;&lt;title&gt;LED Control&lt;/title&gt;\n&quot;; ptr +=&quot;&lt;style&gt;html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}\n&quot;; ptr +=&quot;body{margin-top: 50px;} h1 {color: #444444;margin: 50px auto 30px;} h3 {color: #444444;margin-bottom: 50px;}\n&quot;; ptr +=&quot;.button {display: block;width: 80px;background-color: #1abc9c;border: none;color: white;padding: 13px 30px;text-decoration: none;font-size: 25px;margin: 0px auto 35px;cursor: pointer;border-radius: 4px;}\n&quot;; ptr +=&quot;.button-cw {background-color: #1abc9c;}\n&quot;; ptr +=&quot;.button-cw:active {background-color: #16a085;}\n&quot;; ptr +=&quot;.button-ccw {background-color: #34495e;}\n&quot;; ptr +=&quot;.button-ccw:active {background-color: #2c3e50;}\n&quot;; ptr +=&quot;.button-mstop {background-color: #34495e;}\n&quot;; ptr +=&quot;.button-mstop:active {background-color: #2c3e50;}\n&quot;; ptr +=&quot;p {font-size: 14px;color: #888;margin-bottom: 10px;}\n&quot;; ptr +=&quot;&lt;/style&gt;\n&quot;; ptr +=&quot;&lt;/head&gt;\n&quot;; ptr +=&quot;&lt;body&gt;\n&quot;; ptr +=&quot;&lt;h1&gt;Weather Station&lt;/h1&gt;\n&quot;; ptr +=&quot;&lt;h3&gt;Runs either direction continuously&lt;/h3&gt;\n&quot;; if(cw) {ptr +=&quot;&lt;p&gt;Motor running Clock-wise&lt;/p&gt;&lt;a class=\&quot;button button-off\&quot; href=\&quot;/cw_off\&quot;&gt;Stop&lt;/a&gt;\n&quot;;} else {ptr +=&quot;&lt;p&gt;Motor not running Clock-wise&lt;/p&gt;&lt;a class=\&quot;button button-on\&quot; href=\&quot;/cw_on\&quot;&gt;Run&lt;/a&gt;\n&quot;;} if(ccw) {ptr +=&quot;&lt;p&gt;Motor running Counter Clock-wise&lt;/p&gt;&lt;a class=\&quot;button button-off\&quot; href=\&quot;/ccw_off\&quot;&gt;Stop&lt;/a&gt;\n&quot;;} else {ptr +=&quot;&lt;p&gt;Motor not running Counter Clock-wise&lt;/p&gt;&lt;a class=\&quot;button button-on\&quot; href=\&quot;/ccw_on\&quot;&gt;Run&lt;/a&gt;\n&quot;;} ptr +=&quot;&lt;/body&gt;\n&quot;; ptr +=&quot;&lt;/html&gt;\n&quot;; return ptr; } </code></pre>
<p>At the end of <code>getWeather()</code> you call <code>delay(postingInterval);</code></p> <p><code>postingInterval</code> is set to <code>60*60*1000</code> ... one hour. That means <code>getWeather()</code> won't return for one hour and nothing else in <code>loop()</code> will be processed during that time, including the web server.</p> <p>You need to remove that <code>delay()</code> call and rewrite your loop to check if <code>postingInterval</code> milliseconds have passed and only call <code>getWeather()</code> if they have.</p>
90251
|wire-library|arduino-uno-wifi|
Setup loops: never enters loop - restarting?
2022-07-21T23:13:27.663
<p>I uploaded the following to my UNO with WiFi:</p> <pre><code>#include &lt;SPI.h&gt; #include &lt;Wire.h&gt; #include &quot;Adafruit_CCS811.h&quot; Adafruit_CCS811 ccs; // The air quality sensor String Dataline = &quot;&quot;; void setup() { Wire.begin(); Serial.begin(115200); Serial.println(&quot;SET UP&quot;); } void loop() { // wait a second between measurements. delay(1000); Dataline = &quot;&quot;; Dataline = Dataline + getTime(); Dataline = Dataline + AIRSensor(); Dataline = Dataline + &quot;...&quot;; Serial.println(Dataline); } String getTime() { String OUT = &quot;Tim::&quot;; OUT += String(millis()); return OUT; } String AIRSensor() { if (ccs.available()) { if (!ccs.readData()) { float temp = ccs.calculateTemperature(); String CO2 = (String)ccs.geteCO2(); return &quot;CO2::&quot; + CO2 +&quot;TAQ::&quot; + (String)temp; } } else { return &quot;CO2::-999,TAQ::-999&quot;; } } </code></pre> <p>The output is simply &quot;SET UP&quot; repeated:</p> <pre><code>SET UP SET UP SET UP ... </code></pre> <p>It never enters the loop or prints anything else out. Does this mean the UNO is resetting? How do I troubleshoot?</p>
<p>You can tell that something is going wrong between your <code>println</code>. Some advice in this case: eliminate the <code>String</code> entirely and replace the <code>println</code> with a series of <code>print</code>. This would let you narrow down which function is causing the problem. It also can save some memory, which is a nice bonus in embedded programming.</p> <p>I suspect in this case the problem is your use of C-style casts to <code>String</code> in <code>AIRSensor()</code>. <code>(String)whatever</code> and <code>String(whatever)</code> do very different things, and the former is not something you want here, or something you should be using very often in C++ code.</p> <p>The code in <code>loop</code> is running, but it is crashing and causing the hardware to reset. Since it is crashing before it reaches the first visible behavior in <code>loop</code>, it just looks like <code>setup</code> is running over and over.</p>
90272
|arduino-mega|isp|atmega|
Error while burning bootloader onto ATMega-8A using Arduino Mega 2560: avrdude: invalid byte value
2022-07-23T17:15:56.007
<p>So, I'm trying to burn the bootloader onto an ATMega 8A with an Arduino Mega 2560 as ISP.<br /> I made the necessary connections, and got this error:</p> <pre><code>C:\Program Files (x86)\Arduino\hardware/tools/avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega8 -cstk500v1 -P\\.\COM3 -b19200 -e -Ulock:w:0x3f:m -Uhfuse:w:0b110{bootloader.ckopt_bit}{bootloader.eesave_bit}10{bootloader.bootrst_bit}:m -Ulfuse:w:0b{bootloader.bod_bits}{bootloader.sut_cksel_bits}:m avrdude: Version 5.11, compiled on Sep 2 2011 at 19:38:36 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/ Copyright (c) 2007-2009 Joerg Wunsch System wide configuration file is &quot;C:\Program Files (x86)\Arduino\hardware/tools/avr/etc/avrdude.conf&quot; Using Port : \\.\COM3 Using Programmer : stk500v1 Overriding Baud Rate : 19200 avrdude: Send: 0 [30] [20] avrdude: Send: 0 [30] [20] avrdude: Send: 0 [30] [20] avrdude: Recv: . [14] avrdude: Recv: . [10] AVR Part : ATMEGA8 Chip Erase delay : 10000 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 4 20 128 0 no 512 4 0 9000 9000 0xff 0xff Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- flash 33 10 64 0 yes 8192 64 128 4500 4500 0xff 0x00 Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- lfuse 0 0 0 0 no 1 0 0 2000 2000 0x00 0x00 Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- hfuse 0 0 0 0 no 1 0 0 2000 2000 0x00 0x00 Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- lock 0 0 0 0 no 1 0 0 2000 2000 0x00 0x00 Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- calibration 0 0 0 0 no 4 0 0 0 0 0x00 0x00 Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- signature 0 0 0 0 no 3 0 0 0 0 0x00 0x00 Programmer Type : STK500 Description : Atmel STK500 Version 1.x firmware avrdude: Send: A [41] . [80] [20] avrdude: Recv: . [14] avrdude: Recv: . [02] avrdude: Recv: . [10] avrdude: Send: A [41] . [81] [20] avrdude: Recv: . [14] avrdude: Recv: . [01] avrdude: Recv: . [10] avrdude: Send: A [41] . [82] [20] avrdude: Recv: . [14] avrdude: Recv: . [12] avrdude: Recv: . [10] avrdude: Send: A [41] . [98] [20] avrdude: Recv: . [14] avrdude: Recv: . [00] avrdude: Recv: . [10] Hardware Version: 2 Firmware Version: 1.18 Topcard : Unknown avrdude: Send: A [41] . [84] [20] avrdude: Recv: . [14] avrdude: Recv: . [00] avrdude: Recv: . [10] avrdude: Send: A [41] . [85] [20] avrdude: Recv: . [14] avrdude: Recv: . [00] avrdude: Recv: . [10] avrdude: Send: A [41] . [86] [20] avrdude: Recv: . [14] avrdude: Recv: . [00] avrdude: Recv: . [10] avrdude: Send: A [41] . [87] [20] avrdude: Recv: . [14] avrdude: Recv: . [00] avrdude: Recv: . [10] avrdude: Send: A [41] . [89] [20] avrdude: Recv: . [14] avrdude: Recv: . [00] avrdude: Recv: . [10] Vtarget : 0.0 V Varef : 0.0 V Oscillator : Off SCK period : 0.1 us avrdude: Send: A [41] . [81] [20] avrdude: Recv: . [14] avrdude: Recv: . [01] avrdude: Recv: . [10] avrdude: Send: A [41] . [82] [20] avrdude: Recv: . [14] avrdude: Recv: . [12] avrdude: Recv: . [10] avrdude: Send: B [42] p [70] . [00] . [00] . [01] . [01] . [01] . [01] . [02] . [ff] . [00] . [ff] . [ff] . [00] @ [40] . [02] . [00] . [00] . [00] [20] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [10] avrdude: Send: E [45] . [05] . [04] . [d7] . [c2] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [10] avrdude: Send: P [50] [20] avrdude: Recv: . [14] avrdude: Recv: . [10] avrdude: AVR device initialized and ready to accept instructions Reading | avrdude: Send: V [56] 0 [30] . [00] . [00] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [1e] avrdude: Recv: . [10] avrdude: Send: V [56] 0 [30] . [00] . [01] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [93] avrdude: Recv: . [10] ################avrdude: Send: V [56] 0 [30] . [00] . [02] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [07] avrdude: Recv: . [10] ################################## | 100% 0.06s avrdude: Device signature = 0x1e9307 avrdude: Send: V [56] . [a0] . [01] . [fc] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [ff] avrdude: Recv: . [10] avrdude: Send: V [56] . [a0] . [01] . [fd] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [ff] avrdude: Recv: . [10] avrdude: Send: V [56] . [a0] . [01] . [fe] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [ff] avrdude: Recv: . [10] avrdude: Send: V [56] . [a0] . [01] . [ff] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [ff] avrdude: Recv: . [10] avrdude: erasing chip avrdude: Send: V [56] . [ac] . [80] . [00] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [00] avrdude: Recv: . [10] avrdude: Send: A [41] . [81] [20] avrdude: Recv: . [14] avrdude: Recv: . [01] avrdude: Recv: . [10] avrdude: Send: A [41] . [82] [20] avrdude: Recv: . [14] avrdude: Recv: . [12] avrdude: Recv: . [10] avrdude: Send: B [42] p [70] . [00] . [00] . [01] . [01] . [01] . [01] . [02] . [ff] . [00] . [ff] . [ff] . [00] @ [40] . [02] . [00] . [00] . [00] [20] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [10] avrdude: Send: E [45] . [05] . [04] . [d7] . [c2] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [10] avrdude: Send: P [50] [20] avrdude: Recv: . [14] avrdude: Recv: . [10] avrdude: reading input file &quot;0x3f&quot; avrdude: writing lock (1 bytes): Writing | avrdude: Send: V [56] X [58] . [00] . [00] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [ff] avrdude: Recv: . [10] ################################################## | 100% 0.02s avrdude: 1 bytes of lock written avrdude: verifying lock memory against 0x3f: avrdude: load data lock data from input file 0x3f: avrdude: input file 0x3f contains 1 bytes avrdude: reading on-chip lock data: Reading | avrdude: Send: V [56] X [58] . [00] . [00] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [ff] avrdude: Recv: . [10] ################################################## | 100% 0.02s avrdude: verifying ... avrdude: 1 bytes of lock verified avrdude: reading input file &quot;0b110{bootloader.ckopt_bit}{bootloader.eesave_bit}10{bootloader.bootrst_bit}&quot; avrdude: invalid byte value (0b110{bootloader.ckopt_bit}{bootloader.eesave_bit}10{bootloader.bootrst_bit}) specified for immediate mode avrdude: read from file '0b110{bootloader.ckopt_bit}{bootloader.eesave_bit}10{bootloader.bootrst_bit}' failed avrdude: Send: Q [51] [20] avrdude: Recv: . [14] avrdude: Recv: . [10] avrdude done. Thank you. </code></pre> <p>These are my fuse bits:</p> <pre><code># General 8.name=ATmega8 (8MHz Internal Clock on breadboard) 8.upload.tool=avrdude 8.upload.maximum_data_size=1024 8.bootloader.tool=avrdude 8.bootloader.unlock_bits=0x3f 8.bootloader.lock_bits=0x0f 8.bootloader.low_fuses=0b{bootloader.bod_bits}{bootloader.sut_cksel_bits} 8.bootloader.high_fuses=0b110{bootloader.ckopt_bit}{bootloader.eesave_bit}10{bootloader.bootrst_bit} 8.build.core=MCUdude_corefiles 8.build.variant=standard 8.build.board=AVR_ATmega8 8.build.mcu=atmega8 8.build.bootloader_led=B5 # Upload port select 8.menu.bootloader.uart0=Yes (UART0) 8.menu.bootloader.uart0.upload.maximum_size=7680 8.menu.bootloader.uart0.upload.protocol=arduino 8.menu.bootloader.uart0.upload.port=UART0 8.menu.bootloader.uart0.build.export_merged_output=true 8.menu.bootloader.uart0.bootloader.bootrst_bit=0 8.menu.bootloader.uart0.bootloader.file=optiboot_flash/bootloaders/{build.mcu}/{build.f_cpu}/optiboot_flash_{build.mcu}_{upload.port}_{upload.speed}_{build.f_cpu}_{build.bootloader_led}.hex 8.menu.bootloader.no_bootloader=No bootloader 8.menu.bootloader.no_bootloader.upload.maximum_size=8192 8.menu.bootloader.no_bootloader.build.export_merged_output=false 8.menu.bootloader.no_bootloader.bootloader.bootrst_bit=1 8.menu.bootloader.no_bootloader.bootloader.file=empty/empty.hex # EEPROM 8.menu.eeprom.keep=EEPROM retained 8.menu.eeprom.keep.bootloader.eesave_bit=0 8.menu.eeprom.erase=EEPROM not retained 8.menu.eeprom.erase.bootloader.eesave_bit=1 # Brown out detection - This is the first part of the low fuse bit concatenation 8.menu.BOD.2v7=BOD 2.7V 8.menu.BOD.2v7.bootloader.bod_bits=10 8.menu.BOD.4v0=BOD 4.0V 8.menu.BOD.4v0.bootloader.bod_bits=00 8.menu.BOD.disabled=BOD disabled 8.menu.BOD.disabled.bootloader.bod_bits=11 # Compiler link time optimization 8.menu.LTO.Os=LTO disabled 8.menu.LTO.Os.compiler.c.extra_flags= 8.menu.LTO.Os.compiler.c.elf.extra_flags= 8.menu.LTO.Os.compiler.cpp.extra_flags= 8.menu.LTO.Os.ltoarcmd=avr-ar 8.menu.LTO.Os_flto=LTO enabled 8.menu.LTO.Os_flto.compiler.c.extra_flags=-Wextra -flto -g 8.menu.LTO.Os_flto.compiler.c.elf.extra_flags=-w -flto -g 8.menu.LTO.Os_flto.compiler.cpp.extra_flags=-Wextra -flto -g 8.menu.LTO.Os_flto.ltoarcmd=avr-gcc-ar 8.menu.clock.8MHz_internal=8 MHz internal 8.menu.clock.8MHz_internal.upload.speed=38400 8.menu.clock.8MHz_internal.bootloader.sut_cksel_bits=100100 8.menu.clock.8MHz_internal.bootloader.ckopt_bit=1 8.menu.clock.8MHz_internal.build.f_cpu=8000000L </code></pre> <p>Should I try deleting unnescessary stuff from the fuse bits?</p> <p>I tried checking the fuse bits, but they're pretty much alien to me. Any help is welcome.<br /> Thanks in advance<br /> Me</p> <p>Edit: I am using Arduino IDE v1.0.5 and have selected &quot;Arduino as ISP&quot; in the programmer.</p>
<p>1.0.5 is from 2013 and a lot has changed in the IDE since then, particularly between the 1.0.x versions and the 1.5.x versions. Most people wind up with 1.0.5 because it's in the Ubuntu's (and other Linux distribution's) package repo(s).</p> <p>Anyway, it's likely that this old version doesn't define some of the things your board definition is referencing. E.g. you're referring to names that exist in the 1.8.x platform.txt file that don't exist in the 1.0.5 IDE. When the IDE fails to replace a key placeholder, it leaves it like you're seeing in your avrdude commandline: <code>-Uhfuse:w:0b110{bootloader.ckopt_bit}{bootloader.eesave_bit}10{bootloader.bootrst_bit}:m -Ulfuse:w:0b{bootloader.bod_bits}{bootloader.sut_cksel_bits}:m </code> You should not be seeing these <code>{blah}</code> references in your command-lines when compiling or uploading.</p> <p>Actually, 1.0.5 predates the handling of <a href="https://arduino.github.io/arduino-cli/0.23/platform-specification/#custom-board-options" rel="nofollow noreferrer"><code>.menu.</code> style properties</a>. E.g. They used to have entire separate boards.txt entries for the <a href="https://github.com/arduino/Arduino/blob/1.0.5/hardware/arduino/boards.txt#L65" rel="nofollow noreferrer">ATMega328P based nano</a> and the <a href="https://github.com/arduino/Arduino/blob/1.0.5/hardware/arduino/boards.txt#L86" rel="nofollow noreferrer">ATMega168 based nano</a> and these are now handled by a single board with a <a href="https://github.com/arduino/ArduinoCore-avr/blob/1.8.5/boards.txt#L208-L253" rel="nofollow noreferrer"><code>.menu.cpu.</code> section</a> for the selection of the MCU used. So under 1.0.5 none of your <code>.menu.</code> properties are failing to be replaced by the IDE.</p> <p>So, I would start by getting rid of the old IDE and instead installing the latest <a href="https://www.arduino.cc/en/software" rel="nofollow noreferrer">from the official site</a> and seeing if that improves things.</p> <p>That said, if you want to use the ATMega8A with Arduino it would probably be better to use <a href="https://github.com/MCUdude/MiniCore" rel="nofollow noreferrer">MCUdude MiniCore</a> rather than modifying the regular boards.txt file. You'll need a new IDE in order to use that anyway.</p>