├── .gitignore ├── AnalyzerDetails.md ├── GettingStarted.md ├── LICENSE ├── PICOBuildNotes.md ├── PICO_Sigrok_Rates.PNG ├── README.md ├── SerialProtocol.md ├── SigrokBuildNotes.md ├── pico_pgen ├── CMakeLists.txt └── pico_sdk_pgen.c ├── pico_sdk_sigrok ├── CMakeLists.txt ├── build │ └── pico_sdk_sigrok.uf2 ├── pico_sdk_import.cmake ├── pico_sdk_sigrok.c ├── sr_device.c └── sr_device.h └── pulseview └── Readme.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore list for the project 2 | **/.vscode/.browse.c_cpp.db* 3 | **/.vscode/c_cpp_properties.json 4 | **/.vscode/launch.json 5 | **/build/** 6 | 7 | # Except the following files 8 | !*.uf2 -------------------------------------------------------------------------------- /AnalyzerDetails.md: -------------------------------------------------------------------------------- 1 | Running sigrok cli or pulseview at debug level 2 is highly recommended to see reported issues with user configurations. 2 | 3 | ![alt text](https://github.com/pico-coder/sigrok-pico/blob/main/PICO_Sigrok_Rates.PNG) 4 | ## Channels 5 | 6 | ### 21 Digital Channels 7 | Digital channels are PICO board pins D2-D22 and are named accordingly in sigrok. Channels must be enabled (via Pulseview or sigrokcli) starting at D2 and continuously set towards D22 8 | 9 | ### 3 Analog Channels 10 | Any combinations of A0 (ADC0 pin 31),A1(ADC1 pin 32) and A2(ADC2 pin 34) can be enabled. 11 | Channels are only 7 bit accurate because: 12 | 1) Even though the ADC gives a 12 bit value, the ENOB of the RP2040 is only ~8 bits. 13 | 2) 7 bits makes an easy wire encoding that avoids ASCII characters that can be messed up by serial drivers (see SerialProtocol.md) 14 | 3) 7 bits still gives 20mV accuracy and 128 divisions which is usually plenty of separation. 15 | 16 | ### Disabling channels 17 | Note that disabling any unused channels will often reduce serial transfer overhead and allocate more trace storage for the enabled signals, so always disabled unused channels. 18 | 19 | 20 | ## Trigger Modes 21 | HW triggering via PIO was supported in earlier versions, but removed in rev2 because: 22 | 1) There was some issue where it seemed to false trigger when the triggering condition wasn't present. 23 | 2) There was no clear way to specify HW vs Sw triggering in pulseview, especially when the change was made to specify sample rate via a dropdown selection. 24 | If needed you could clone the code for the device and reenable the one line that enabled the triggering. 25 | Note that in the rev2 release the triggers are now sent to the device. The device doesn't use them because the processing overhead for HW triggering is so high that it reduces the effective streaming rate below that of continuous software triggering on the host, and thus adds no value. 26 | 27 | ### SW triggered via libsigrok 28 | Any one or more enabled digital pins can be use for triggering in this mode. Only digital pins are used for triggering, but analog is captured in sync with the digital triggers. 29 | 30 | SW triggers supports level, rising, falling, and changing across all channels. The triggers are specified in the triggering definition of pulseview or sigrokcli. 31 | A pre-capture ratio of 0 to 100% can also be specified. The pre capture buffer will only fill to the ratio if sufficient pretrigger samples are seen. 32 | Note that SW triggering adds substantial host side processing, and such processing on slower processors may limit the maximum usable streaming sample rate. 33 | 34 | ### Always trigger 35 | If no trigger is specified, then the device will immediately capture data of a fixed length. 36 | 37 | ## Storage Modes 38 | The device supports two modes of storage of samples, Fixed Depth and Continuous streaming. Fixed depth is enabled if the trigger mode is Always Trigger and the requested number of samples fits in the device storage space. 39 | Continuous streaming is enabled at all other times, thus any time SW triggering is enabled, or the number of samples is greater than the internal depth. 40 | Fixed depth is a preferred mode because it guarantees that the device can store the samples and send them to host as USB transfer rates allow. 41 | In continuous streaming it is possible that the required bandwidth to issue the samples is greater than the available USB bandwidth. 42 | Thus the user must make a tradeoff between guaranteed capture of limited depth, or larger depths with possible loss. 43 | The device can detect overflow cases in Continuous Streaming mode and send an abort code to the host which is reported to Pulseview. 44 | Abort cases in Continous stream will cause the total number of samples to be reduced, but should not allow corrupted values to be sent. 45 | 46 | ## Sample rate 47 | For better usability, the user is given a fixed set of sample rates in pulseview. The user is given the ability to specify sample rates that may be beyond the capacity of the device to store internally or to transfer to the host in time. 48 | 49 | It is up to the user to understand the limitations below and use accordingly, but the host driver will limit sample rates and print errors and warnings when limits are exceeded. 50 | 51 | If multiple ADC channels are enabled, the specified sample rate is the rate per channel. 52 | Since the RP2040 only supports one ADC conversion at a time the actual ADC rate must 2x or 3x the specified sample rate for 2 channel or 3 channel ADC. 53 | Note that while pulseview displays the ADC samples together in time, they are actually staggered due to the single conversion limitation. 54 | 55 | Sample rate limitations come in two types, hard and soft. 56 | Hard limitations are intrinsic to the how the device functions and are enforced by the libsigrok driver. 57 | If the user specifies sample rates the break the hard limits the driver will report error error messages from Pulseview and/or the sigrok cli 58 | if level 2 verbosity or higher is set. 59 | 60 | Soft limitations are recommendations that if not followed may cause aborts. 61 | Specifically they are related to the ability of the device to send sample data across the USB serial interface before the DMA updates overflow the storage buffers. 62 | Soft limitations are detected by the device when it sees a sample overflow issue and sends an abort signal to the host. 63 | 64 | The protocol supports a run length encoding (RLE) for all digital only sample modes which reduces the amount of data sent on the wire. 65 | Assuming a high frequency sample rate of a relatively on low duty factor signals, RLE may allow Continous Streaming and SW triggering of signals that may not otherwise be possible. 66 | 67 | ## Sample rate hard limits 68 | ### Common sample rate 69 | The PIO and ADC share a common sample rate. This is because libsigrok only supports a common rate and because it keeps the device DMA implementation sane. 70 | ### Sample rate granularity 71 | The sample rate granularity is limited to the a granularity of the clock divisors of the PIO and ADC. The ADC uses only the integer part of the fractional divisor of the 48Mhz USB clock. 72 | The PIO uses the full fractional divisor of the sysclk which is set to 120Mhz (the maximum supported PIO rate). 73 | Pulseview only provides frequencies which yield integer divisors for the PIO and ADC clocks to ensure that the two clocks do not drift over time which can happen with non integer divisors. 74 | The command line interface will allow any specified frequency. It is recommended that for digital modes that integer divisors of 120Mhz be specified to get sample rates close to what is specified (i.e. 120,60,40,30,20,15,12,10Msps etc). 75 | As the sample rate is decreased the granularity increases. 76 | Since the ADC has a maximum frequency of 500khz off a 48Mhz clock it has a minimum divisor of 96 and thus a worst case granularity of 5khz. 77 | ### Min and Max Sample rates. 78 | The minimum sample rate is 5Khz to ensure the sample rate is within the 16 bit divisor. 79 | The maximum sample rate for digital only is 120Msps. 80 | If 8 or more digital channels are enabled sample rates of 60Msps or less are recommended to allow the DMA engine to do a read modify write operation from the PIO FIFO to memory. 81 | Faster rates might work, or they might not... 82 | ## Sample rate soft limits 83 | Soft limits are hard to quantify because they can be based on the maximum USB link bandwidth, or the ability of the device to process and send samples, or on the ability of the host to process samples (especially in SW trigger modes). 84 | Based on testing with a Raspberry PI Model 3B+, the USB port reaches a maximum of 300KB-400KB/sec on the 12Mbit USB link. 85 | Soft limits can be completely avoided by not using SW triggers and setting trace depths that enable Fixed Sample modes, but a particular protocol may not be practical to trace with those restrictions. 86 | In the D4 optimized RLE mode, each byte on the wire holds a 4 bit sample value and a 0-7 sample RLE value, or an 8-640 sample RLE value. 87 | Thus in this mode, it should be possible to Continuous Stream at a sample rate of 300ksps regardless of the sampled data activity. If the activity factor is less, then higher sample rates are possible. 88 | For instance a 20% AF signal has been captured at a sample rate of 2 Msps. 89 | In the other digital only modes, each groups of 7 channels or sent in one byte and a one byte RLE encoding is used. 90 | In mixed digital/analog or analog only modes, each 7 bits of digital data takes one byte, and each analog sample takes a byte. So a 12 bit digital trace with 2 analog channels takes 4 bytes per sample. 91 | 92 | ## Debug UART 93 | The hardware UART0 prints debug information to UART0 TX at 115200bps in rev1, and 921600 for rev2 and beyond. 94 | Since the sigrok driver on the host tries to report most user errors it is not required for use. However, if you are filing a bug sighting having that output could be very useful. 95 | -------------------------------------------------------------------------------- /GettingStarted.md: -------------------------------------------------------------------------------- 1 | Warning: Getting the pico device to work on windows can be an initially frustrating experience, but usually the problem resolves itself. 2 | Recommended steps to resolve issues: 3 | 1) Close out any programs that access serial ports as windows won't allow multiple apps to access a port. 4 | 2) Once pulseview is installed, do a reboot. 5 | 3) Possibly use zadig to map the USB device (I apologize that it's been so long I can't really remember if zadig is atually needed). 6 | 4) Try plugging/unplugging the device and/or opening closing pulseview a few times. 7 | 5) Close pulseview, and open a serial device apps (Terraterm/Putty etc). Send a "*" and then a "i" for identify and you should get a response. For some reason, other apps seem to have more success accessing the device than does the libserial code in pulseview. 8 | 6) Go back and repeat any of the steps above. (Yeah, I know it's frustrating, but eventually it seems to work for most folks). 9 | 10 | It is recommended that you read through the AnalyzerDetails.md for specifics on modes of the device, but if you just can't wait: 11 | 12 | 1) Get some 1Kohm or greater resistors to put inline between the PICO inputs, you don't want to accidentally fry your PICO because you put in voltages <0V or >3.3V or accidentally jumpered ground to VCC. 13 | 2) Get the [sigrok-pico/pico_sdk_sigrok/build/pico_sdk_sigrok.uf2](./pico_sdk_sigrok/build/pico_sdk_sigrok.uf2) file and program it to your PICO devices (examples are online, everywhere). 14 | 3) Install Pulseview and skip to step 7, or sigrok-cli - follow descriptions from the sigrok pages for both. 15 | 4) Replug the PICO to reset it, and then use sigrok-cli to scan for avaliable serial ports 16 | ``` 17 | sigrok-cli --list-serial 18 | ``` 19 | 5) Use sigrok-cli to scan for the device based on the serial port you found above. The baudrate doesn't matter because we are CDC serial. 20 | ``` 21 | sigrok-cli -l 2 -d raspberrypi-pico:conn=/dev/ttyACM0:serialcomm=115200/flow=0 --scan 22 | ``` 23 | 6) Do a first trace 24 | ``` 25 | ~/github/sigrok-cli/sigrok-cli -l 2 -d raspberrypi-pico:conn=/dev/ttyACM0:serialcomm=115200/flow=0 --config samplerate=10000 --channels D2,D3,D4,D5 --samples 1000 26 | ``` 27 | 7) Aternatively to using sigrok-cli use Pulseview. 28 | 8) Go read AnalyzerDetails.md like you should have to begin with.... 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /PICOBuildNotes.md: -------------------------------------------------------------------------------- 1 | Building the RP2040 device code should be nearly exact to building any other Raspberry Pi PICO C SDK build as described in the "getting-started-with-pico". 2 | 1) Setup the PICO C SDK and go through the example builds using cmake and make 3 | 2) git clone this repo to . 4 | 3) cd /sigrok-pico 5 | 4) copy pico_sdk_import.cmake from your pico-sdk repo to /sigrok_pico 6 | 5) export PICO_SDK_PATH= 7 | 6) cd /sigrok-pico 8 | 7) mkdir build 9 | 8) cd build 10 | 9) cmake .. 11 | 10) make 12 | -------------------------------------------------------------------------------- /PICO_Sigrok_Rates.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pico-coder/sigrok-pico/bb28a3fd059783bcc86ec3845f059f0a3eacc675/PICO_Sigrok_Rates.PNG -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | As of 28 Sept 2023 this pull request has been merged into mainline sigrok (https://github.com/sigrokproject/libsigrok/pull/181) 2 | It is highly recommended to install Nightly build from https://sigrok.org/wiki/Downloads (PulseView 0.4.2 and sigrok-cli 0.7.2 do not support sigrok-pico) 3 | 4 | 5 | Please start with the Getting Started page : https://github.com/pico-coder/sigrok-pico/blob/main/GettingStarted.md 6 | ///////////////////////////////////////////////////////////////// 7 | Building this repo: 8 | Bbuilding is not recommended, but some people insist on trying.....) 9 | 10 | I once did a cross compile of PulseView for windows. The instructions and installer are left in place for historical reference, they are likely out of date. 11 | Instructions to download my build are here https://github.com/pico-coder/sigrok-pico/blob/main/pulseview/Readme.md 12 | Again, please use the main sigrok installer. 13 | 14 | For linux, many people have managed to combine my pull request into a libsigrok build. If you are on linux it's probably a practical experiment to try. 4GB of RAM is recommended for pulseview builds to avoid disk swap issues. See SigrokBuildNotes.md 15 | 16 | # 17 | # sigrok-pico 18 | Use a raspberry pi pico (rp2040) as a logic analyzer and oscilloscope with sigrok. 19 | This implementation uses the pico SDK CDC serial library to communicate with sigrok-cli/pulseview through a sigrok driver. 20 | 21 | ## Directories: 22 | 23 | pico_pgen is a simple digital function generator useful for creating patterns to test. 24 | 25 | pico_sdk_sigrok is the pico sdk C code for the PICO RP2040 device. 26 | 27 | The latest libsigrok code exists as a fork at https://github.com/pico-coder/libsigrok 28 | 29 | ## Files 30 | PICOBuildNotes.md - build notes for building the PICO device assuming you have gone through the PICO C SDK "getting started with PICO". 31 | 32 | SigrokBuildNotes.md - rough libsigrok build notes which will be depracated once raspberrypi_pico is mainline 33 | 34 | GettingStarted.md - quick run down on setting things up. 35 | 36 | AnalyzerDetails.md - details on supported modes of the analyzer and various limitations. 37 | 38 | SerialProtocol.md - details of the "over the wire" protocol used between the sigrok driver and the device. 39 | -------------------------------------------------------------------------------- /SerialProtocol.md: -------------------------------------------------------------------------------- 1 | # Protocol Overview 2 | The serial transfers can be grouped into 4 flows. 3 | 1) A configuration and control protocol for setting up sample rates, channel enables, triggering etc. 4 | 2) A general data transfer protocol for any configuration that uses analog channels or more than 4 digital channels 5 | 3) An optimized protocol for digital only configures with 4 or fewer channels that includes run length encoding. 6 | 4) A final byte count used at the end of the general data transfer or optimized protocol 7 | # Configuration and Control - Host to Device 8 | The '*' and '+' are the only two characters that are commands by themselves and do not have any acknowledgement from the device. All other control signals require a character followed by \n or \r, and expect a response as described in each command. 9 | 10 | '*' - An asterisk sent from the host to device is a reset of the current sampling state of the device. It terminates any pending sampling and data transfers and clears sample counts and puts the device in an idle state. It does not effect the USB CDC/Serial link state. The sigrok device driver sends this as the first part of the initial device scan, and at the start of all acquisitions. 11 | 12 | '+' - A plus sent from the host to the device indicates a host forced abort of an in progress capture, which can only be initiated by clicking the stop button in pulseview during an in progress capture. It terminates the sending of data, but does not restore as much state as a reset. 13 | # Configuration and Control commands the require a response with data. 14 | These commands require the device to return with a character string. If the device considers the command to be incorrect, no response is sent and the host driver will timeout and error. 15 | 16 | 'i' - Identify. This is sent from the sigrok scan function to identify the device. The device replys with a string of the format "SRPICO,AxxyDzz,00". The "SRPICO," is a fixed identifier. The "Axx" value is the letter 'A' followed by a two character decimal field identifying the number of analog channels. The y indicates the number of bytes that are used to send analog samples across the wire, for now only the value of 1 is supported. The "Dzz" is the letter 'D' followed by a two character decimal field indicating the number of digital channels supported. The final "00" indicates a version number , which for now is always "00". Thus the full featured 3 analog and 21 digitial channel build returns "SRPICO,A03D21,00". 17 | 18 | 'a' - Analog Scale and offset. The host sends a "Ax" where is X is the channel number, asking the device what scale and offset to apply the sent value to create a floating point value. The device returns with a string of the format "aaaaxbbbbb", where the "aaa" represent the scale in uVolts, the x is the letter 'x', and "bbbb" represent the offset in uVolts. Both the scale and offset can be variable length up to a combined 18 characters. Both scale and offset should support negative signs. 19 | # Configuration and Control commands that respond with ack. 20 | If the device receives these commands and considers the values appropriate it returns a single "*", otherwise is returns nothing and the device driver will timeout in error. 21 | 22 | 'R' - Sets the sample rate. The 'R' is followed by a decimal value string indicating the sample rate, such as "R100000". 23 | 24 | 'L' -Sets the sample limit, i.e. the total number of samples. The 'L' is followed by a decimal value string indicating the number of samples, such as "L5000". 25 | 26 | 'A' - Analog channel enable. These are of the format "Axyy" where x is 0 for disabled, 1 for enabled and yy is the channel number. Thus "A103" enables analog channel 3. 27 | 28 | 'D' - Digital channel enable. These are of the format "Dxyy" where x is 0 for disabled, 1 for enabled and yy is the channel number. Thus "D020" disables analog channel 20. 29 | # Configuration and Control commands with no response. 30 | These commands do not expect an acknowledgement of any kind because they initiate data capture/transfer. 31 | 32 | 'F' - Fixed Sample mode - tells the device to grab a fixed set of samples. This is used in all cases where SW based triggering is not enabled. 33 | 34 | 'C' - Continous Sample mode - tells the device to continuously transfer data because SW triggering is processing the data stream to find a trigger. 35 | 36 | # Device to host commands. 37 | '!' - Device detected abort - this is the only command sent by the device that is not initiated by a command from the host. It is used in cases where the device has detected a capture overflow condition and is no longer sending more data. The device will periodically send this until the host sends a '*' or '+'. 38 | 39 | # General Data transfer protocol. 40 | This is used for all cases where any analog channels are enabled, or more than 4 digital channels are enabled. 41 | Samples of digital and analog data are sent in groups where for a given point in time the values of each channel are sent. A sample for each digital and analog channel is sent as one slice of information, rather than sending all of the sample data for a given channel at once. Data samples are sent first where each transmitted byte is the value of a group of 7 digital channels,OR'd with 0x80 so that no ASCII control characters are used. Lowest channels are sent first. Each enabled analog channel is then sent where it's 7 bit sample value is also OR'd with 0x80 to avoid ASCII control characters. 42 | 43 | For example, assume 14 digital channels (D2 to D15) and 2 analog channels, a "slice" of sample data might be sent as: 0x8F, 0xA3, 0x91, 0xB6. 44 | 45 | That would indicate Digital Channels 8:2 are 0xF, Channels 15:9 are 0x23, Analog channel A0 is 0x11 and Analog Channel A1 is 0x36. 46 | 47 | # Optimized 4 Digital channel protocol with Run Length Encoding (RLE). 48 | There are many narrow width high speed protocols (I2C,I2S,SPI) which may require sample rates higher than the 300kB to 500kB transfer rates supported by the Serial CDC interface. For cases where transactions are in bursts of activity surrounded by low activity, a run length encoding scheme is enabled to reduce wire transfer bandwidth and enable sampling rates higher than that supported by the protocol. 49 | 50 | 51 | -------------------------------------------------------------------------------- /SigrokBuildNotes.md: -------------------------------------------------------------------------------- 1 | With the release to mainline libsigrok, there are no special build commands neeed, follow whatever the latest recommendations are on the main sigrok pages. 2 | As a warning, trying to resolve all of the library dependencies on your given OS/VM etc. is the greatest challenge. That is intrinsic to building PulseView in general, not to to this library. 3 | It is generally recommended to try to get the sigrok-cli built and operational first, as that will ensure you have the correct USB/serial and other libraries. 4 | Good-luck! 5 | -------------------------------------------------------------------------------- /pico_pgen/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.13) 2 | 3 | include(pico_sdk_import.cmake) 4 | 5 | project(test_project C CXX ASM) 6 | set(CMAKE_C_STANDARD 11) 7 | set(CMAKE_CXX_STANDARD 17) 8 | pico_sdk_init() 9 | 10 | add_executable(pico_sdk_pgen 11 | pico_sdk_pgen.c 12 | ) 13 | 14 | pico_enable_stdio_usb(pico_sdk_pgen 0) 15 | pico_enable_stdio_uart(pico_sdk_pgen 1) 16 | 17 | pico_add_extra_outputs(pico_sdk_pgen) 18 | 19 | target_link_libraries( 20 | pico_sdk_pgen 21 | pico_stdlib 22 | 23 | ) 24 | -------------------------------------------------------------------------------- /pico_pgen/pico_sdk_pgen.c: -------------------------------------------------------------------------------- 1 | //simple generator 2 | //Mask of bits 22:2 to use as outputs - 3 | #define GPIO_D_MASK 0x7FFFFC 4 | 5 | #include 6 | #include "pico/stdlib.h" 7 | #include "hardware/gpio.h" 8 | #include "stdarg.h" 9 | #include 10 | 11 | 12 | int main(){ 13 | 14 | long int i,j; 15 | 16 | // set_sys_clock_khz(250000,true); 17 | // uart_set_format(uart0,8,1,1); 18 | // uart_init(uart0,115200); 19 | stdio_init_all(); 20 | gpio_set_function(0, GPIO_FUNC_UART); 21 | gpio_set_function(1, GPIO_FUNC_UART); 22 | sleep_us(100000); 23 | printf("\n\n\nhello from pgen \r\n\n\n"); 24 | //Use 22:2 as digital 25 | gpio_init_mask(GPIO_D_MASK); //set as GPIO_FUNC_SIO and clear output enable 26 | gpio_set_dir_masked(GPIO_D_MASK,GPIO_D_MASK); //TODO - I think an out can still be an ind? 27 | uint32_t ctime,tstart; 28 | uint32_t cval; 29 | tstart=time_us_32(); 30 | while(true){ 31 | ctime=time_us_32(); 32 | // shift up/down to test performance with rle etc 33 | //cval=(ctime-tstart)<<4; //not a true 62.5ns/8Mhz wave, but will increment as such 34 | //cval=(ctime-tstart)<<2; //not a true 250ns/2Mhz wave, but will increment as such 35 | //cval=(ctime-tstart); //1us, 500kz 36 | //cval=(ctime-tstart)>>1; //2us, 256khz 37 | //cval=(ctime-tstart)>>3; //8us, 64khz 38 | cval=(ctime-tstart)>>5; //32us, 16khz 39 | //cval=(ctime-tstart)>>6; //64us, 8khz 40 | //cval=(ctime-tstart)>>7; //128us, 4khz 41 | //cval=(ctime-tstart)>>9; //512us, 1khz 42 | //cval=(ctime-tstart)>>11; //2ms, 250hz 43 | //cval=0x123456789; 44 | //Note: both the mask and the value must be shifted up by the starting number of bits 45 | gpio_put_masked(GPIO_D_MASK,cval<<2); 46 | //printf("cval 0x%X",cval); 47 | }//while true 48 | 49 | 50 | 51 | }//main 52 | -------------------------------------------------------------------------------- /pico_sdk_sigrok/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # == DO NOT EDIT THE FOLLOWING LINES for the Raspberry Pi Pico VS Code Extension to work == 2 | if(WIN32) 3 | set(USERHOME $ENV{USERPROFILE}) 4 | else() 5 | set(USERHOME $ENV{HOME}) 6 | endif() 7 | set(sdkVersion 2.1.0) 8 | set(toolchainVersion 13_3_Rel1) 9 | set(picotoolVersion 2.1.0) 10 | set(picoVscode ${USERHOME}/.pico-sdk/cmake/pico-vscode.cmake) 11 | if (EXISTS ${picoVscode}) 12 | include(${picoVscode}) 13 | endif() 14 | # ==================================================================================== 15 | set(PICO_BOARD pico CACHE STRING "Board type") 16 | 17 | cmake_minimum_required(VERSION 3.13) 18 | 19 | include(pico_sdk_import.cmake) 20 | 21 | project(pico_sdk_sigrok C CXX ASM) 22 | set(CMAKE_C_STANDARD 11) 23 | set(CMAKE_CXX_STANDARD 17) 24 | pico_sdk_init() 25 | 26 | add_executable(pico_sdk_sigrok 27 | pico_sdk_sigrok.c 28 | sr_device.c 29 | ) 30 | 31 | pico_enable_stdio_usb(pico_sdk_sigrok 1) 32 | pico_enable_stdio_uart(pico_sdk_sigrok 0) 33 | 34 | pico_add_extra_outputs(pico_sdk_sigrok) 35 | 36 | target_link_libraries( 37 | pico_sdk_sigrok 38 | pico_stdlib 39 | hardware_adc 40 | hardware_dma 41 | hardware_pio 42 | hardware_sync 43 | pico_multicore 44 | pico_stdio_usb 45 | ) 46 | -------------------------------------------------------------------------------- /pico_sdk_sigrok/build/pico_sdk_sigrok.uf2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pico-coder/sigrok-pico/bb28a3fd059783bcc86ec3845f059f0a3eacc675/pico_sdk_sigrok/build/pico_sdk_sigrok.uf2 -------------------------------------------------------------------------------- /pico_sdk_sigrok/pico_sdk_import.cmake: -------------------------------------------------------------------------------- 1 | # This is a copy of /external/pico_sdk_import.cmake 2 | 3 | # This can be dropped into an external project to help locate this SDK 4 | # It should be include()ed prior to project() 5 | 6 | if (DEFINED ENV{PICO_SDK_PATH} AND (NOT PICO_SDK_PATH)) 7 | set(PICO_SDK_PATH $ENV{PICO_SDK_PATH}) 8 | message("Using PICO_SDK_PATH from environment ('${PICO_SDK_PATH}')") 9 | endif () 10 | 11 | if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT} AND (NOT PICO_SDK_FETCH_FROM_GIT)) 12 | set(PICO_SDK_FETCH_FROM_GIT $ENV{PICO_SDK_FETCH_FROM_GIT}) 13 | message("Using PICO_SDK_FETCH_FROM_GIT from environment ('${PICO_SDK_FETCH_FROM_GIT}')") 14 | endif () 15 | 16 | if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_PATH} AND (NOT PICO_SDK_FETCH_FROM_GIT_PATH)) 17 | set(PICO_SDK_FETCH_FROM_GIT_PATH $ENV{PICO_SDK_FETCH_FROM_GIT_PATH}) 18 | message("Using PICO_SDK_FETCH_FROM_GIT_PATH from environment ('${PICO_SDK_FETCH_FROM_GIT_PATH}')") 19 | endif () 20 | 21 | if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_TAG} AND (NOT PICO_SDK_FETCH_FROM_GIT_TAG)) 22 | set(PICO_SDK_FETCH_FROM_GIT_TAG $ENV{PICO_SDK_FETCH_FROM_GIT_TAG}) 23 | message("Using PICO_SDK_FETCH_FROM_GIT_TAG from environment ('${PICO_SDK_FETCH_FROM_GIT_TAG}')") 24 | endif () 25 | 26 | if (PICO_SDK_FETCH_FROM_GIT AND NOT PICO_SDK_FETCH_FROM_GIT_TAG) 27 | set(PICO_SDK_FETCH_FROM_GIT_TAG "master") 28 | message("Using master as default value for PICO_SDK_FETCH_FROM_GIT_TAG") 29 | endif() 30 | 31 | set(PICO_SDK_PATH "${PICO_SDK_PATH}" CACHE PATH "Path to the Raspberry Pi Pico SDK") 32 | set(PICO_SDK_FETCH_FROM_GIT "${PICO_SDK_FETCH_FROM_GIT}" CACHE BOOL "Set to ON to fetch copy of SDK from git if not otherwise locatable") 33 | set(PICO_SDK_FETCH_FROM_GIT_PATH "${PICO_SDK_FETCH_FROM_GIT_PATH}" CACHE FILEPATH "location to download SDK") 34 | set(PICO_SDK_FETCH_FROM_GIT_TAG "${PICO_SDK_FETCH_FROM_GIT_TAG}" CACHE FILEPATH "release tag for SDK") 35 | 36 | if (NOT PICO_SDK_PATH) 37 | if (PICO_SDK_FETCH_FROM_GIT) 38 | include(FetchContent) 39 | set(FETCHCONTENT_BASE_DIR_SAVE ${FETCHCONTENT_BASE_DIR}) 40 | if (PICO_SDK_FETCH_FROM_GIT_PATH) 41 | get_filename_component(FETCHCONTENT_BASE_DIR "${PICO_SDK_FETCH_FROM_GIT_PATH}" REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}") 42 | endif () 43 | # GIT_SUBMODULES_RECURSE was added in 3.17 44 | if (${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.17.0") 45 | FetchContent_Declare( 46 | pico_sdk 47 | GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk 48 | GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG} 49 | GIT_SUBMODULES_RECURSE FALSE 50 | ) 51 | else () 52 | FetchContent_Declare( 53 | pico_sdk 54 | GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk 55 | GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG} 56 | ) 57 | endif () 58 | 59 | if (NOT pico_sdk) 60 | message("Downloading Raspberry Pi Pico SDK") 61 | FetchContent_Populate(pico_sdk) 62 | set(PICO_SDK_PATH ${pico_sdk_SOURCE_DIR}) 63 | endif () 64 | set(FETCHCONTENT_BASE_DIR ${FETCHCONTENT_BASE_DIR_SAVE}) 65 | else () 66 | message(FATAL_ERROR 67 | "SDK location was not specified. Please set PICO_SDK_PATH or set PICO_SDK_FETCH_FROM_GIT to on to fetch from git." 68 | ) 69 | endif () 70 | endif () 71 | 72 | get_filename_component(PICO_SDK_PATH "${PICO_SDK_PATH}" REALPATH BASE_DIR "${CMAKE_BINARY_DIR}") 73 | if (NOT EXISTS ${PICO_SDK_PATH}) 74 | message(FATAL_ERROR "Directory '${PICO_SDK_PATH}' not found") 75 | endif () 76 | 77 | set(PICO_SDK_INIT_CMAKE_FILE ${PICO_SDK_PATH}/pico_sdk_init.cmake) 78 | if (NOT EXISTS ${PICO_SDK_INIT_CMAKE_FILE}) 79 | message(FATAL_ERROR "Directory '${PICO_SDK_PATH}' does not appear to contain the Raspberry Pi Pico SDK") 80 | endif () 81 | 82 | set(PICO_SDK_PATH ${PICO_SDK_PATH} CACHE PATH "Path to the Raspberry Pi Pico SDK" FORCE) 83 | 84 | include(${PICO_SDK_INIT_CMAKE_FILE}) 85 | -------------------------------------------------------------------------------- /pico_sdk_sigrok/pico_sdk_sigrok.c: -------------------------------------------------------------------------------- 1 | //Raspberry Pi PICO/RP2040 code to implement a logic analyzer and oscilloscope 2 | 3 | /** 4 | * Some Original code from the pico examples project: 5 | * Copyright (c) 2020 Raspberry Pi (Trading) Ltd. 6 | * SPDX-License-Identifier: BSD-3-Clause 7 | */ 8 | 9 | #include 10 | #include "pico/stdlib.h" //uart definitions 11 | #include //atoi,atol, malloc 12 | #include "hardware/gpio.h" 13 | #include "hardware/pio.h" 14 | #include "hardware/adc.h" 15 | #include "hardware/dma.h" 16 | #include "hardware/structs/bus_ctrl.h" 17 | #include "hardware/uart.h" 18 | #include "hardware/clocks.h" 19 | #include "pico/multicore.h" 20 | #include "tusb.h"//.tud_cdc_write... 21 | 22 | #include "sr_device.h" 23 | 24 | //NODMA is a debug mode that disables the DMA engine and prints raw PIO FIFO outputs 25 | //it is limited to testing a small number of samples equal to the PIO FIFO depths 26 | //#define NODMA 1 27 | //These two enable debug print outs of D4 generation, D4_DBG2 are consider higher verbosity 28 | //#define D4_DBG 1 29 | //#define D4_DBG2 2 30 | 31 | uint8_t *capture_buf; 32 | volatile uint32_t c1cnt=0; 33 | volatile uint32_t c0cnt=0; 34 | sr_device_t dev; 35 | volatile uint32_t tstart; 36 | volatile bool send_resp=false; 37 | uint8_t txbuf[TX_BUF_SIZE]; 38 | uint16_t txbufidx; 39 | uint32_t rxbufdidx; 40 | uint32_t rlecnt; 41 | uint32_t ccnt=0; //count of characters sent serially 42 | //Number of bytes stored as DMA per slice, must be 1,2 or 4 to support aligned access 43 | //This will be be zero for 1-4 digital channels. 44 | uint8_t d_dma_bps; 45 | uint32_t samp_remain; 46 | uint32_t lval,cval; //last and current digital sample values 47 | uint32_t num_halves; //track the number of halves we have processed 48 | 49 | volatile uint32_t *tstsa0,*tstsa1,*tstsd0,*tstsd1; 50 | volatile uint32_t *taddra0,*taddra1,*taddrd0,*taddrd1; 51 | volatile int lowerhalf; //are we processing the upper or lower half of the data buffers 52 | volatile bool mask_xfer_err; 53 | 54 | //The function stdio_usb_out_chars is part of the PICO sdk usb library. 55 | //However the function is not externally visible from the library and rather than 56 | //figure out the build dependencies to do that it is just copied here. 57 | //This is much faster than a printf of the string, and even faster than the puts_raw 58 | //supported by the PICO SDK stdio library, which doesn't allow the known length of the buffer 59 | //to be specified. (The C standard write function doesn't seem to work at all). 60 | //This function also avoids the inserting of CR/LF in certain modes. 61 | //The tud_cdc_write_available function returns 256, and thus we have a 256B buffer to feed into 62 | //but the CDC serial issues in groups of 64B. 63 | //Since there is another memory fifo inside the TUD code this might possibly be optimized 64 | //to directly write to it, rather than writing txbuf. That might allow faster rle processing 65 | //but is a bit too complicated. 66 | 67 | void my_stdio_usb_out_chars(const char *buf, int length) { 68 | static uint64_t last_avail_time; 69 | uint32_t owner; 70 | if (tud_cdc_connected()) { 71 | for (int i = 0; i < length;) { 72 | int n = length - i; 73 | int avail = (int) tud_cdc_write_available(); 74 | if (n > avail) n = avail; 75 | if (n) { 76 | int n2 = (int) tud_cdc_write(buf + i, (uint32_t)n); 77 | tud_task(); 78 | tud_cdc_write_flush(); 79 | i += n2; 80 | last_avail_time = time_us_64(); 81 | } else { 82 | tud_task(); 83 | tud_cdc_write_flush(); 84 | if (!tud_cdc_connected() || 85 | (!tud_cdc_write_available() && time_us_64() > last_avail_time + PICO_STDIO_USB_STDOUT_TIMEOUT_US)) { 86 | break; 87 | } 88 | } 89 | } 90 | } else { 91 | // reset our timeout 92 | last_avail_time = 0; 93 | } 94 | } 95 | 96 | 97 | //This is an optimized transmit of trace data for configurations with 4 or fewer digital channels 98 | //and no analog. Run length encoding (RLE) is used to send counts of repeated values to effeciently utilize 99 | //USB CDC link bandwidth. This is the only mode where a given serial byte can have both sample information 100 | //and RLE counts. 101 | //Samples from PIO are dma'd in 32 bit words, each containing 8 samples of 4 bits (1 nibble). 102 | //RLE Encoding: 103 | //Values 0x80-0xFF encode an rle cnt of a previous value with a new value: 104 | // Bit 7 is 1 to distinguish from the rle only values. 105 | // Bits 6:4 indicate a run length up to 7 cycles of the previous value 106 | // Bits 3:0 are the new value. 107 | //For longer runs, an RLE only encoding uses decimal values 48 to 127 (0x30 to 0x7F) 108 | //as x8 run length values of 8..640. 109 | //All other ascii values (except from the abort and the end of run byte_cnt) are reserved. 110 | uint32_t send_slices_D4(sr_device_t *d,uint8_t *dbuf){ 111 | uint8_t nibcurr,niblast; 112 | uint32_t cword,lword; //current and last word 113 | uint32_t *cptr; 114 | txbufidx=0; 115 | //Don't optimize the first word (eight samples) perfectly, just send them to make the for loop easier, 116 | //and setup the initial conditions for rle tracking 117 | cptr=(uint32_t *) &(dbuf[0]); 118 | cword=*cptr; 119 | #ifdef D4_DBG 120 | Dprintf("Dbuf %p cptr %p data 0x%X\n\r",(void *)&(dbuf[0]),(void *) cptr,cword); 121 | #endif 122 | lword=cword; 123 | for (int j=0;j<8;j++){ 124 | nibcurr=cword&0xF; 125 | txbuf[j]=(nibcurr)|0x80; 126 | cword>>=4; 127 | } 128 | niblast=nibcurr; 129 | cptr=(uint32_t *) &(txbuf[0]); 130 | txbufidx=8; 131 | rxbufdidx=4; 132 | rlecnt=0; 133 | 134 | if(d->samples_per_half<=8){ 135 | my_stdio_usb_out_chars(txbuf,txbufidx); 136 | d->scnt+=d->samples_per_half; 137 | return txbufidx; 138 | } 139 | //chngcnt=8; 140 | //The total number of 4 bit samples remaining to process from this half. 141 | //Subtract 8 because we procesed the word above. 142 | samp_remain=d->samples_per_half-8; 143 | 144 | //If in fixed sample (non-continous mode) only send the amount of samples requested 145 | if((d->cont==false)&&((d->scnt+samp_remain)>(d->num_samples))){ 146 | samp_remain=d->num_samples-d->scnt; 147 | d->scnt+=samp_remain; 148 | }else{ 149 | d->scnt+=d->samples_per_half; 150 | } 151 | //Process one word (8 samples) at a time. 152 | for(int i=0;i<(samp_remain>>3);i++) { 153 | cptr=(uint32_t *) &(dbuf[rxbufdidx]); 154 | cword=*cptr; 155 | rxbufdidx+=4; 156 | #ifdef D4_DBG2 157 | Dprintf("dbuf0 %p dbufr %p cptr %p \n\r",dbuf,&(dbuf[rxbufdidx]),cptr); 158 | #endif 159 | //Send maximal RLE counts in this outer section to the txbuf, and if we accumulate a few of them 160 | //push to the device so that we don't accumulate large numbers 161 | //of unsent RLEs. That allows the host to process them gradually rather than in a flood 162 | //when we get a value change. 163 | while(rlecnt>=640){ 164 | txbuf[txbufidx++]=127; 165 | rlecnt-=640; 166 | if(txbufidx>3){ 167 | my_stdio_usb_out_chars(txbuf,txbufidx); 168 | ccnt+=txbufidx; 169 | txbufidx=0; 170 | } 171 | } 172 | //Coarse rle looks across the full word and allows a faster compare in cases with low activity factors 173 | //We must make sure cword==lword and that all nibbles of cword are the same 174 | if((cword==lword)&&((cword>>4)==(cword&0x0FFFFFFF))){ 175 | rlecnt+=8; 176 | #ifdef D4_DBG2 177 | Dprintf("coarse word 0x%X\n\r",cword); 178 | #endif 179 | } 180 | else{//if coarse rle didn't match 181 | #ifdef D4_DBG2 182 | Dprintf("cword 0x%X nibcurr 0x%X i %d rx idx %u rlecnt %u \n\r",cword,nibcurr,i,rxbufdidx,rlecnt); 183 | #endif 184 | lword=cword; 185 | for (int j=0;j<8;j++){ //process all 8 nibbles 186 | nibcurr=cword&0xF; 187 | if(nibcurr==niblast) { 188 | rlecnt++; 189 | } 190 | else{ 191 | //If the value changes we must push all remaing rles to the txbuf 192 | //chngcnt++; 193 | //Send intermediate 8..632 RLEs 194 | if(rlecnt>7) { 195 | int rlemid=rlecnt&0x3F8; 196 | txbuf[txbufidx++]=(rlemid>>3)+47; 197 | } 198 | //And finally the 0..7 rle along with the new value 199 | rlecnt&=0x7; 200 | #ifdef D4_DBG2 //print when sample value changes 201 | Dprintf("VChang val 0x%X rlecnt %d i%d j%d \n\r",nibcurr,rlecnt,i,j); 202 | #endif 203 | txbuf[txbufidx++]=0x80|nibcurr|rlecnt<<4; 204 | rlecnt=0; 205 | }//nibcurr!=last 206 | cword>>=4; 207 | niblast=nibcurr; 208 | }//for j 209 | } //else (not a coarse rle ) 210 | #ifdef D4_DBG2 211 | Dprintf("i %d rx idx %u rlecnt %u \n\r",i,rxbufdidx,rlecnt); 212 | Dprintf("i %u tx idx %d bufs 0x%X 0x%X 0x%X\n\r",i,txbufidx,txbuf[txbufidx-3],txbuf[txbufidx-2],txbuf[txbufidx-1]); 213 | #endif 214 | //Emperically found that transmitting groups of around 32B gives optimum bandwidth 215 | if(txbufidx>=64){ 216 | my_stdio_usb_out_chars(txbuf,txbufidx); 217 | ccnt+=txbufidx; 218 | txbufidx=0; 219 | } 220 | }//for i in samp_send>>3 221 | //At the end of processing the half send any residual samples as we don't maintain state between the halves 222 | //Maximal 640 values first 223 | while(rlecnt>=640){ 224 | txbuf[txbufidx++]=127; 225 | rlecnt-=640; 226 | } 227 | //Middle rles 8..632 228 | if(rlecnt>7) { 229 | int rleend=rlecnt&0x3F8; 230 | txbuf[txbufidx++]=(rleend>>3)+47; 231 | } 232 | //1..7 RLE 233 | //The rle and value encoding counts as both a sample count of rle and a new sample 234 | //thus we must decrement rlecnt by 1 and resend the current value which will match the previous values 235 | //(if the current value didn't match, the rlecnt would be 0). 236 | if(rlecnt){ 237 | rlecnt&=0x7; 238 | rlecnt--; 239 | txbuf[txbufidx++]=0x80|nibcurr|rlecnt<<4; 240 | rlecnt=0; 241 | } 242 | if(txbufidx){ 243 | my_stdio_usb_out_chars(txbuf,txbufidx); 244 | ccnt+=txbufidx; 245 | txbufidx=0; 246 | } 247 | 248 | }//send_slices_D4 249 | 250 | //Send a digital sample of multiple bytes with the 7 bit encoding 251 | void inline tx_d_samp(sr_device_t *d,uint32_t cval){ 252 | for(char b=0;b < d->d_tx_bps;b++){ 253 | txbuf[txbufidx++]=(cval|0x80); 254 | cval>>=7; 255 | } 256 | } 257 | 258 | //Allow for 1,2 or 4B reads of sample data to reduce memory read overhead when 259 | //parsing digital sample data. This function is correct for all uses, but if included 260 | //the compiled code is substantially slower to the point that digital only transfers 261 | //can't keep up with USB rate. Thus it is only used by the send_slices_analog which is already 262 | //limited to 500khz, and in the starting send_slice_init. 263 | uint32_t get_cval(uint8_t *dbuf){ 264 | uint32_t cval; 265 | if(d_dma_bps==1){ 266 | cval=dbuf[rxbufdidx]; 267 | }else if(d_dma_bps==2){ 268 | cval=(*((uint16_t *) (dbuf+rxbufdidx))); 269 | }else{ 270 | cval=(*((uint32_t *) (dbuf+rxbufdidx))); 271 | //To make a 32bit value written from PIO we pull in IOs that aren't actuall 272 | //digital channels so mask them off 273 | cval<<=11; 274 | cval>>=11; 275 | } 276 | rxbufdidx+=d_dma_bps; 277 | return cval; 278 | } 279 | /*RLE encoding for 5-21 channels has two ranges. 280 | Decimal 48 to 79 are RLEs of 1 to 32 respectively. 281 | Decimal 80 to 127 are (N-78)*32 thus 64,96..80,120..1568 282 | Note that it is the responsibility of the caller to 283 | forward txbuf bytes to USB to prevent txbufidx from overflowing the size 284 | of txbuf. We do not always push to USB to reduce its impact 285 | on performance. 286 | */ 287 | void inline check_rle(){ 288 | while(rlecnt>=1568){ 289 | txbuf[txbufidx++]=127; 290 | rlecnt-=1568; 291 | } 292 | if(rlecnt>32){ 293 | uint16_t rlediv=rlecnt>>5; 294 | txbuf[txbufidx++]=rlediv+78;//was 86; 295 | rlecnt-=rlediv<<5; 296 | } 297 | if(rlecnt){ 298 | txbuf[txbufidx++]=47+rlecnt; 299 | rlecnt=0; 300 | } 301 | } 302 | 303 | //Send txbuf to usb based on an input threshold 304 | void check_tx_buf(uint16_t cnt){ 305 | if(txbufidx>=cnt){ 306 | my_stdio_usb_out_chars(txbuf,txbufidx); 307 | ccnt+=txbufidx; 308 | txbufidx=0; 309 | } 310 | } 311 | //Common init for send_slices_1B/2B/4B, but not D4 or analog 312 | void send_slice_init(sr_device_t *d,uint8_t *dbuf){ 313 | rxbufdidx=0; 314 | //Adjust the number of samples to send if there are more in the dma buffer 315 | //then we need. 316 | samp_remain=d->samples_per_half; 317 | if((d->cont==false)&&((d->scnt+samp_remain)>(d->num_samples))){ 318 | samp_remain=d->num_samples-d->scnt; 319 | d->scnt+=samp_remain; 320 | }else{ 321 | d->scnt+=d->samples_per_half; 322 | } 323 | txbufidx=0; 324 | //Always send the first sample to establish a previous value for RLE 325 | //the use of get_cval is inefficient, but only done once per half buffer 326 | lval=get_cval(dbuf); 327 | //If we are in 4B mode shift off invalid bits 328 | lval<<=11; 329 | lval>>=11; 330 | tx_d_samp(d,lval); 331 | samp_remain--; 332 | rlecnt=0; 333 | 334 | } 335 | //There are three very similar functions send_slices_1B/2B/4B. 336 | //Each of which is very similar but exist because if a common function 337 | //is used with the get_cval in the inner loop, the performance drops 338 | //substantially. Thus each function has a 1,2, or 4B aligned read respectively. 339 | //We can just always read a 4B value because the core doesn't support non-aligned accesses. 340 | //These must be marked noinline to ensure they remain separate functions for good performance 341 | //1B is 5-8 channels 342 | void __attribute__ ((noinline)) send_slices_1B(sr_device_t *d,uint8_t *dbuf){ 343 | send_slice_init(d,dbuf); 344 | for(int s=0;s>=11; 388 | if(cval==lval){ 389 | rlecnt++; 390 | } 391 | else{ 392 | check_rle(); 393 | tx_d_samp(d,cval); 394 | check_tx_buf(TX_BUF_THRESH); 395 | }//if cval!=lval 396 | lval=cval; 397 | }//for s 398 | check_rle(); 399 | check_tx_buf(1); 400 | }//send_slices_4B 401 | 402 | 403 | //Slice transmit code, used for all cases with any analog channels 404 | //All digital channels for one slice are sent first in 7 bit bytes using values 0x80 to 0xFF 405 | //Analog channels are sent next, with each channel taking one 7 bit byte using values 0x80 to 0xFF. 406 | //This does not support run length encoding because it's not clear how to define RLE on analog signals 407 | uint32_t send_slices_analog(sr_device_t *d,uint8_t *dbuf,uint8_t *abuf){ 408 | uint32_t rxbufaidx=0; 409 | rxbufdidx=0; 410 | samp_remain=d->samples_per_half; 411 | if((d->cont==false)&&((d->scnt+samp_remain)>(d->num_samples))){ 412 | samp_remain=d->num_samples-d->scnt; 413 | d->scnt+=samp_remain; 414 | }else{ 415 | d->scnt+=d->samples_per_half; 416 | } 417 | txbufidx=0; 418 | uint32_t lval=0; 419 | for(int s=0;sd_mask){ 421 | cval=get_cval(dbuf); 422 | tx_d_samp(d,cval); 423 | //Dprintf("s %d cv %X bps %d idx t %d r %d \n\r",s,cval,d_dma_bps,txbufidx,rxbufdidx); 424 | } 425 | for(char i=0;ia_chan_cnt;i++){ 426 | txbuf[txbufidx]=(abuf[rxbufaidx]>>1)|0x80; 427 | txbufidx++; 428 | rxbufaidx++; 429 | //Dprintf("av %X cnt %d idx t %d r %d\n\r",abuf[rxbufaidx-1],d->a_chan_cnt,txbufidx,rxbufaidx); 430 | } 431 | //Since this doesn't support RLEs we don't need to buffer 432 | //extra bytes to prevent txbuf overflow, but this value 433 | //works well anyway 434 | check_tx_buf(TX_BUF_THRESH); 435 | }//for s 436 | check_tx_buf(1); 437 | }//send_slices_analog 438 | 439 | 440 | //See if a given half's dma engines are idle and if so process the data, update the write pointer and 441 | //ensure that when done the other dma is still busy indicating we didn't lose data . 442 | //int __not_in_flash_func(check_half)(sr_device_t *d,volatile uint32_t *tstsa0,volatile uint32_t *tstsa1,volatile uint32_t *tstsd0, 443 | int check_half(sr_device_t *d,volatile uint32_t *tstsa0,volatile uint32_t *tstsa1,volatile uint32_t *tstsd0, 444 | volatile uint32_t *tstsd1,volatile uint32_t *t_addra0,volatile uint32_t *t_addrd0, 445 | uint8_t *d_start_addr,uint8_t *a_start_addr, bool mask_xfer_err){ 446 | int a0busy,d0busy; 447 | uint64_t stime,etime,dtime; 448 | volatile uint32_t *piodbg1,*piodbg2; 449 | volatile uint8_t piorxstall1,piorxstall2; 450 | stime=time_us_64(); 451 | a0busy=((*tstsa0)>>24)&1; 452 | d0busy=((*tstsd0)>>24)&1; 453 | 454 | if(((a0busy==0)||(d->a_mask==0)) 455 | &&((d0busy==0)||(d->d_mask==0))){ 456 | //Use two dma controllers where each writes half of the trace space. 457 | //When one half finishes we send it's data while the other dma controller writes to the other half. 458 | //We rely on DMA chaining where one completing dma engine triggers the next. 459 | //When chaining happens the original target address is not restored so we must rewrite the starting address. 460 | //Also when chaining is enabled we can get into an infinite loop where we ping pong between each other. 461 | //and it is possible that if the other DMA controller finishes before we have send our half of the data that 462 | //our DMA controller will startup and overwrite our data. That is the DMA overflow condition. 463 | //We don't actually overflow the DMA, but instead we fail to establish proper chaining to keep the 464 | //ping pong going. 465 | //The only way to avoid the overflow condition is to reduce the sampling rate so that the transmit of samples 466 | //can keep up, or do a fixed sample that fits into the sample buffer. 467 | //When we first enter the loop it is assumed that the other controller is not chained to us so that if we don't 468 | //process in time then our DMA controller won't be started by the other. That assumption is maintained by 469 | //always pointing our DMA engine to itself so tht in the next function call it is the "other" controller. 470 | //We then process our half's samples and send to USB. 471 | //When done we confirm that the other channel is still active, and if so we know we haven't overflowed and thus 472 | //can establish the chain from the other channel to us. If the other channel is not still active, or if the 473 | //PIO/ADC FIFOs indicates an RXstall condition which indicates PIO lost samples, then we abort. 474 | //Note that in all cases we should never actually send any corrupted data we just send less than what was requested. 475 | //Note that we must use the "alias" versions of the DMA CSRs to prevent writes from triggering them. 476 | //Since we swap the csr pointers we determine the other half from the address offsets. 477 | uint8_t myachan=(((uint32_t) tstsa0)>>6)&0xF; 478 | uint8_t otherachan=(((uint32_t) tstsa1)>>6)&0xF; 479 | uint8_t mydchan=(((uint32_t)tstsd0)>>6)&0xF; 480 | uint8_t otherdchan=(((uint32_t)tstsd1)>>6)&0xF; 481 | // Dprintf("my stts pre a 0x%X d 0x%X\n\r",*tstsa0,*tstsd0); 482 | //Set my chain to myself so that I can't chain to the other. 483 | volatile uint32_t ttmp; 484 | ttmp=((tstsd0[1])&0xFFFF87FF)|mydchan<<11; 485 | tstsd0[1]=ttmp; 486 | ttmp=((tstsa0[1])&0xFFFF87FF)|myachan<<11; 487 | tstsa0[1]=ttmp; 488 | (*t_addra0)=(uint32_t) a_start_addr; 489 | (*t_addrd0)=(uint32_t) d_start_addr; 490 | 491 | piodbg1=(volatile uint32_t *)(PIO0_BASE+0x8); //PIO DBG 492 | piorxstall1=(((*piodbg1)&0x1)&&(d->d_mask!=0)); 493 | 494 | 495 | 496 | if(d->a_mask){ 497 | send_slices_analog(d,d_start_addr,a_start_addr); 498 | } 499 | else if(d_dma_bps==0){ 500 | send_slices_D4(d,d_start_addr); 501 | } 502 | else if(d_dma_bps==1){ 503 | send_slices_1B(d,d_start_addr); 504 | } 505 | else if(d_dma_bps==2){ 506 | send_slices_2B(d,d_start_addr); 507 | } 508 | else{ 509 | send_slices_4B(d,d_start_addr); 510 | } 511 | 512 | if((d->cont==false)&&(d->scnt>=d->num_samples)){ 513 | d->sending=false; 514 | } 515 | 516 | //Set my other chain to me 517 | //use aliases here as well to prevent triggers 518 | ttmp=((tstsd1[1])&0xFFFF87FF)|mydchan<<11; 519 | tstsd1[1]=ttmp; 520 | ttmp=((tstsa1[1])&0xFFFF87FF)|myachan<<11; 521 | tstsa1[1]=ttmp; 522 | num_halves++; 523 | piodbg2=(volatile uint32_t *)(PIO0_BASE+0x8); //PIO DBG 524 | piorxstall2=((*piodbg2)&0x1)&&(d->d_mask!=0); 525 | volatile uint32_t *adcfcs; 526 | uint8_t adcfail; 527 | adcfcs=(volatile uint32_t *)(ADC_BASE+0x8);//ADC FCS 528 | adcfail=(((*adcfcs) & 0xC00)&&(d->a_mask)) ? 1 : 0; 529 | //if(adcfail){Dprintf("adcfcs 0x%X %p\n\r",*adcfcs,(void *) adcfcs);} 530 | //Ensure other dma is still busy, if not that means we have samples from PIO/ADC that could be lost. 531 | //It's only an error if we haven't already gotten the samples we need, or if we are processing the first 532 | //half and all the remaining samples we need are in the 2nd half. 533 | //Note that in continuous mode num_samples isn't defined. 534 | uint8_t proc_fail; 535 | proc_fail=(~(((((*tstsa1)>>24)&1)||(d->a_mask==0)) 536 | &&((((*tstsd1)>>24)&1)||(d->d_mask==0)))&1); 537 | //Dprintf("pf 0x%X 0x%X %d\n\r",*tstsa1,*tstsd1,proc_fail); 538 | // if(mask_xfer_err 539 | // || ((piorxstall1==0) 540 | // &&((((*tstsa1)>>24)&1)||(d->a_mask==0)) 541 | // &&((((*tstsd1)>>24)&1)||(d->d_mask==0)))){ 542 | if(mask_xfer_err 543 | || ((piorxstall1==0) 544 | &&(adcfail==0) 545 | &&(piorxstall2==0) 546 | &&(proc_fail==0))){ 547 | // Dprintf("h\n\r"); 548 | return 1; 549 | }else{ 550 | 551 | if(piorxstall1 || piorxstall2){ 552 | Dprintf("***Abort PIO RXSTALL*** %d %d half %d\n\r",piorxstall1,piorxstall2,num_halves); 553 | } 554 | if(proc_fail){ 555 | Dprintf("***Abort DMA ovrflow*** half %d \n\r",num_halves); 556 | } 557 | if(adcfail){ 558 | Dprintf("***Abort ADC ovrflow*** half %d \n\r",num_halves); 559 | } 560 | d->aborted=true; 561 | //Issue end of trace markers to host 562 | //The main loop also sends these periodically until the host is done.. 563 | my_stdio_usb_out_chars("!!!",3); 564 | //Dprintf("scnt %u \n\r",d->scnt); 565 | //Dprintf("a st %u msk %u\n\r",(*tstsa1),d->a_mask); 566 | //Dprintf("d st %u msk %u\n\r",(*tstsd1),d->d_mask); 567 | return -1; 568 | } 569 | }//if not busy 570 | return 0; 571 | }//check_half 572 | //Check if dma activity is complete. This was split out to allow core1 to do the monitoring 573 | //and slice processing and leave usb interrupt handling to core 0, but doing so did not improve 574 | //streaming performance, so it's left in core0. 575 | void dma_check(sr_device_t *d){ 576 | if(d->sending&& d->started && ((d->scntnum_samples)||d->cont)){ 577 | uint32_t a,b; 578 | int ret; 579 | c0cnt++; 580 | if(lowerhalf){ 581 | ret=check_half(&dev,tstsa0,tstsa1,tstsd0,tstsd1,taddra0,taddrd0, 582 | &(capture_buf[d->dbuf0_start]),&(capture_buf[d->abuf0_start]),mask_xfer_err); 583 | 584 | if(ret==1){ 585 | lowerhalf=0; 586 | } 587 | else if(ret<0) {d->sending=false;} 588 | } 589 | if(lowerhalf==0){ 590 | ret=check_half(&dev,tstsa1,tstsa0,tstsd1,tstsd0,taddra1,taddrd1, 591 | &(capture_buf[d->dbuf1_start]),&(capture_buf[d->abuf1_start]),mask_xfer_err); 592 | if(ret==1) { 593 | lowerhalf=1; 594 | } 595 | else if(ret<0) {d->sending=false;} 596 | } 597 | }//if sending and started and under numsamples 598 | } 599 | //This is a simple maintenance loop to monitor serial activity so that core0 can be dedicated 600 | //to monitoring DMA activity and sending trace data. 601 | //Most of the time this loop is stalled with wfes (wait for events). 602 | void core1_code(){ 603 | uint32_t testinc=0x0; 604 | int intin; 605 | uint8_t uartch; 606 | uint32_t ctime; 607 | uint32_t cval; 608 | volatile uint32_t *usbctrl; 609 | usbctrl=(volatile uint32_t *)(USBCTRL_BASE); 610 | uint32_t usb_last=1,usb_curr; 611 | while(true){ 612 | //The wait for event (wfe) puts core1 in an idle state 613 | //Each core instruction takes a memory cycle, as does each core memory or IO register read. 614 | //The memory fabric supports up to 4 reads per cycle if there are no bank conflicts 615 | //The DMA engine needs a read of the PIO and ADC and a write of memory 616 | //and thus chances of conflicts are high. Thus once we are in sampling mode slow down C1 to allow 617 | //C0 to loop faster and process faster. 618 | //Without wfes C1 typically completes 10x the number of outer loops as C0, but with the wfes 619 | //C0 completes more loops and C1 activity drops to 1% . 620 | //Much of the C0 code has built in sev (Send Event) but we also add an explicit one in the main while loop 621 | 622 | if(dev.started){ 623 | c1cnt++; 624 | __wfe(); 625 | __wfe(); 626 | __wfe(); 627 | __wfe(); 628 | __wfe(); 629 | __wfe(); 630 | __wfe(); 631 | __wfe(); 632 | __wfe(); 633 | __wfe(); 634 | } 635 | if(dev.started==false){ 636 | //always drain all defined uarts as if that is not done it can 637 | //effect the usb serial CDC stability 638 | //these are generally rare events caused by noise/reset events 639 | //and thus not checked when dev.started 640 | while (uart_is_readable_within_us(uart0, 0)) { 641 | uartch = uart_getc(uart0); 642 | } 643 | } 644 | //look for commands on usb cdc 645 | intin=getchar_timeout_us(0); 646 | //The '+' is the only character we track during normal sampling because it can end 647 | //a continuous trace. A reset '*' should only be seen after we have completed normally 648 | //or hit an error condition. 649 | if(intin=='+'){ 650 | dev.sending=false; 651 | dev.aborted=false; //clear the abort so we stop sending !! 652 | } 653 | //send_resp is used to eliminate all prints from core1 to prevent collisions with 654 | //prints in core0 655 | else if(intin>=0){ 656 | if(process_char(&dev,(char)intin)) 657 | {send_resp=true;} 658 | } 659 | }//while true 660 | 661 | } 662 | 663 | int main(){ 664 | char cmdstr[20]; 665 | int cmdstrptr=0; 666 | char charin,tmpchar; 667 | long int i,j; 668 | uint16_t len; 669 | uint32_t tmpint,tmpint2; 670 | 671 | 672 | dma_channel_config acfg0,acfg1,pcfg0,pcfg1; 673 | uint admachan0,admachan1,pdmachan0,pdmachan1; 674 | PIO pio = pio0; 675 | uint piosm=0; 676 | float ddiv; 677 | int res; 678 | bool init_done=false; 679 | uint64_t starttime,endtime; 680 | set_sys_clock_khz(SYS_CLK_BASE,true); 681 | stdio_usb_init(); 682 | uart_set_format(uart0,8,1,0); 683 | uart_init(uart0,921600); 684 | gpio_set_function(0, GPIO_FUNC_UART); 685 | gpio_set_function(1, GPIO_FUNC_UART); 686 | sleep_us(100000); 687 | Dprintf("\n\rHello from PICO sigrok device \n\r"); 688 | 689 | 690 | uint f_pll_sys = frequency_count_khz(CLOCKS_FC0_SRC_VALUE_PLL_SYS_CLKSRC_PRIMARY); 691 | Dprintf("pll_sys = %dkHz\n\r", f_pll_sys); 692 | uint f_clk_sys = frequency_count_khz(CLOCKS_FC0_SRC_VALUE_CLK_SYS); 693 | Dprintf("clk_sys = %dkHz\n\r", f_clk_sys); 694 | 695 | //Set GPIO23 (TP4) to control switched mode power supply noise 696 | gpio_init_mask(1<<23); 697 | gpio_set_dir_masked(1<<23,1<<23); 698 | gpio_put_masked(1<<23,1<<23); 699 | //Early CDC IO code had lots of sleep statements, but the TUD code seems to have sufficient 700 | //checks that this isn't needed, but it doesn't hurt... 701 | sleep_us(100000); 702 | //GPIOs 26 through 28 (the ADC ports) are on the PICO, GPIO29 is not a pin on the PICO 703 | adc_gpio_init(26); 704 | adc_gpio_init(27); 705 | adc_gpio_init(28); 706 | adc_init(); 707 | 708 | multicore_launch_core1(core1_code); 709 | 710 | 711 | admachan0 = dma_claim_unused_channel(true); 712 | admachan1 = dma_claim_unused_channel(true); 713 | pdmachan0 = dma_claim_unused_channel(true); 714 | pdmachan1 = dma_claim_unused_channel(true); 715 | acfg0 = dma_channel_get_default_config(admachan0); 716 | acfg1 = dma_channel_get_default_config(admachan1); 717 | pcfg0 = dma_channel_get_default_config(pdmachan0); 718 | pcfg1 = dma_channel_get_default_config(pdmachan1); 719 | //ADC transfer 8 bytes, PIO transfer the 4B default 720 | channel_config_set_transfer_data_size(&acfg0, DMA_SIZE_8); 721 | channel_config_set_transfer_data_size(&acfg1, DMA_SIZE_8); 722 | channel_config_set_transfer_data_size(&pcfg0, DMA_SIZE_32); 723 | channel_config_set_transfer_data_size(&pcfg1, DMA_SIZE_32); 724 | channel_config_set_read_increment(&acfg0, false); 725 | channel_config_set_read_increment(&acfg1, false); 726 | channel_config_set_read_increment(&pcfg0, false); 727 | channel_config_set_read_increment(&pcfg1, false); 728 | channel_config_set_write_increment(&acfg0, true); 729 | channel_config_set_write_increment(&acfg1, true); 730 | channel_config_set_write_increment(&pcfg0, true); 731 | channel_config_set_write_increment(&pcfg1, true); 732 | 733 | // Pace transfers based on availability of ADC samples 734 | channel_config_set_dreq(&acfg0, DREQ_ADC); 735 | channel_config_set_dreq(&acfg1, DREQ_ADC); 736 | volatile uint32_t *tcounta0,*tcounta1,*tcountd0,*tcountd1; 737 | tcounta0=(volatile uint32_t *)(DMA_BASE+0x40*admachan0+0x8); //DMA_TRANS_COUNT offset 738 | tcounta1=(volatile uint32_t *)(DMA_BASE+0x40*admachan1+0x8); //DMA_TRANS_COUNT offset 739 | tcountd0=(volatile uint32_t *)(DMA_BASE+0x40*pdmachan0+0x8); //DMA_TRANS_COUNT offset 740 | tcountd1=(volatile uint32_t *)(DMA_BASE+0x40*pdmachan1+0x8); //DMA_TRANS_COUNT offset 741 | 742 | //Use the debug version of the count registers because the count of the DMA_TRANS_COUNT is not 743 | //visible if it is not active 744 | volatile uint32_t *tcountdbga0,*tcountdbga1,*tcountdbgd0,*tcountdbgd1; 745 | tcountdbga0=(volatile uint32_t *)(DMA_BASE+0x40*admachan0+0x804); //DMA_TRANS_COUNT DBGoffset 746 | tcountdbga1=(volatile uint32_t *)(DMA_BASE+0x40*admachan1+0x804); //DMA_TRANS_COUNT DBGoffset 747 | tcountdbgd0=(volatile uint32_t *)(DMA_BASE+0x40*pdmachan0+0x804); //DMA_TRANS_COUNT DBGoffset 748 | tcountdbgd1=(volatile uint32_t *)(DMA_BASE+0x40*pdmachan1+0x804); //DMA_TRANS_COUNT DBGoffset 749 | 750 | taddra0=(volatile uint32_t *)(DMA_BASE+0x40*admachan0+0x4); //DMA_WRITE_addr offset 751 | taddra1=(volatile uint32_t *)(DMA_BASE+0x40*admachan1+0x4); //DMA_WRITE_addr offset 752 | taddrd0=(volatile uint32_t *)(DMA_BASE+0x40*pdmachan0+0x4); //DMA_WRITE_addr offset 753 | taddrd1=(volatile uint32_t *)(DMA_BASE+0x40*pdmachan1+0x4); //DMA_WRITE_addr offset 754 | 755 | tstsa0=(volatile uint32_t *)(DMA_BASE+0x40*admachan0+0xc); //DMA_WRITE_sts offset 756 | tstsa1=(volatile uint32_t *)(DMA_BASE+0x40*admachan1+0xc); //DMA_WRITE_sts offset 757 | tstsd0=(volatile uint32_t *)(DMA_BASE+0x40*pdmachan0+0xc); //DMA_WRITE_sts offset 758 | tstsd1=(volatile uint32_t *)(DMA_BASE+0x40*pdmachan1+0xc); //DMA_WRITE_sts offset 759 | //PIO status 760 | volatile uint32_t *pioctrl,*piofstts,*piodbg,*pioflvl; 761 | pioctrl=(volatile uint32_t *)(PIO0_BASE); //PIO CTRL 762 | piofstts=(volatile uint32_t *)(PIO0_BASE+0x4); //PIO FSTAT 763 | piodbg=(volatile uint32_t *)(PIO0_BASE+0x8); //PIO DBG 764 | pioflvl=(volatile uint32_t *)(PIO0_BASE+0x10); //PIO FLVL 765 | 766 | volatile uint32_t *pio0sm0clkdiv; 767 | pio0sm0clkdiv=(volatile uint32_t *)(PIO0_BASE+0xc8); 768 | //Give High priority to DMA to ensure we don't overflow the PIO or DMA fifos 769 | //The DMA controller must read across the common bus to read the PIO fifo so enabled both reads and write 770 | bus_ctrl_hw->priority = BUSCTRL_BUS_PRIORITY_DMA_W_BITS | BUSCTRL_BUS_PRIORITY_DMA_R_BITS; 771 | 772 | init(&dev); 773 | //Since RP2040 is 32 bit this should always be 4B aligned, and it must be because the PIO 774 | //does DMA on a per byte basis 775 | //If either malloc fails the code will just hang 776 | Dprintf("Malloc\n\r"); 777 | capture_buf=malloc(DMA_BUF_SIZE); 778 | Dprintf("DMA start %p\n\r",(void *)capture_buf); 779 | //Ensure we leave 10k or more left for any dynamic allocations that need it 780 | uint8_t *tptr; 781 | tptr=malloc(10000); 782 | Dprintf("10K free start %p\n\r",(void *)tptr); 783 | free(tptr); 784 | 785 | //This testmode forces the device into a capture state without needing 786 | //sigrok cli/pulseview to initiate it 787 | //All of the needed fields may not be up to date... 788 | /* 789 | dev.started=false; 790 | dev.cont=false; 791 | dev.sending=true; 792 | dev.a_chan_cnt=0; //count of enabled analog channels 793 | dev.a_mask=0x0; 794 | dev.d_mask=0xF; 795 | dev.d_nps=1; //digital nibbles per slice 796 | dev.sample_rate=1000; 797 | dev.num_samples=5000; 798 | dev.scnt=0; //number of samples sent 799 | ccnt=0; 800 | 801 | */ 802 | 803 | gpio_init_mask(GPIO_D_MASK); //set as GPIO_FUNC_SIO and clear output enable 804 | gpio_set_dir_masked(GPIO_D_MASK,0); //Set all to input 805 | while(1){ 806 | __sev();//send event to wake core1 807 | if(send_resp){ 808 | int mylen=strlen(dev.rspstr); 809 | //Don't mix printf with direct to usb commands 810 | //printf("%s",dev.rspstr); 811 | my_stdio_usb_out_chars(dev.rspstr,mylen); 812 | send_resp=false; 813 | } 814 | //Dprintf("ss %d %d",dev.sending,dev.started); 815 | if(dev.sending && (dev.started==false)) { 816 | //Only boost frequency during a sample so that average device power is less. 817 | //It's not clear that this is needed because rp2040 is pretty low power, but it can't hurt... 818 | #ifdef SYS_CLK_BOOST_EN 819 | //This is not enabled if any analog channels are enabled because due to 820 | //ADC frequency limits the processing rate is never the limiter to performance. 821 | //And maybe it might help avoid an overfrequency issue with ADC...or not... 822 | if(dev.a_chan_cnt==0){ 823 | Dprintf("Boost up\n\r"); 824 | set_sys_clock_khz(SYS_CLK_BOOST_FREQ,true); 825 | //UART is based on sys_clk so must be reprogrammed 826 | uart_init(uart0,UART_BAUD); 827 | } 828 | #endif 829 | lowerhalf=1; 830 | //Sample rate must always be even. Pulseview code enforces this 831 | //because a frequency step of 2 is required to get a pulldown to specify 832 | //the sample rate, but sigrok cli can still pass it. 833 | dev.sample_rate>>=1; 834 | dev.sample_rate<<=1; 835 | //Adjust up and align to 4 to avoid rounding errors etc 836 | if(dev.num_samples<16){dev.num_samples=16;} 837 | dev.num_samples=(dev.num_samples+3)&0xFFFFFFFC; 838 | //Divide capture buf evenly based on channel enables 839 | //d_size is aligned to 4 bytes because pio operates on words 840 | //These are the sizes for each half buffer in bytes 841 | //Calculate relative size in terms of nibbles which is the smallest unit, thus a_chan_cnt is multiplied by 2 842 | //Nibble size storage is only allow for D4 mode with no analog channels enabled 843 | //For instance a D0..D5 with A0 would give 1/2 the storage to digital and 1/2 to analog 844 | uint32_t d_nibbles,a_nibbles,t_nibbles; //digital, analog and total nibbles 845 | d_nibbles=dev.d_nps; //digital is in grous of 4 bits 846 | a_nibbles=dev.a_chan_cnt*2; //1 byte per sample 847 | t_nibbles=d_nibbles+a_nibbles; 848 | 849 | //total buf size must be a multiple of a_nibbles*2, d_nibbles*8, and t_nibbles so that division is always 850 | //in whole samples 851 | //Also set a multiple of 32 because the dma buffer is split in half, and 852 | //the PIO does writes on 4B boundaries, and then a 4x factor for any other size/alignment issues 853 | uint32_t chunk_size=t_nibbles*32; 854 | if(a_nibbles) chunk_size*=a_nibbles; 855 | if(d_nibbles) chunk_size*=d_nibbles; 856 | uint32_t dig_bytes_per_chunk=chunk_size*d_nibbles/t_nibbles; 857 | uint32_t dig_samples_per_chunk=(d_nibbles) ? dig_bytes_per_chunk*2/d_nibbles : 0; 858 | uint32_t chunk_samples=d_nibbles ? dig_samples_per_chunk : (chunk_size*2)/(a_nibbles); 859 | //total chunks in entire buffer-round to 2 since we split it in half 860 | uint32_t buff_chunks=(DMA_BUF_SIZE/chunk_size)&0xFFFFFFFE; 861 | //round up and force power of two since we cut it in half 862 | uint32_t chunks_needed=((dev.num_samples/chunk_samples)+2)&0xFFFFFFFE; 863 | Dprintf("Initial buf calcs nibbles d %d a %d t %d \n\r",d_nibbles,a_nibbles,t_nibbles); 864 | Dprintf("chunk size %d samples %d buff %d needed %d\n\r",chunk_size,chunk_samples,buff_chunks,chunks_needed); 865 | Dprintf("dbytes per chunk %d dig samples per chunk %d\n\r",dig_bytes_per_chunk,dig_samples_per_chunk); 866 | //If all of the samples we need fit in two half buffers or less then we can mask the error 867 | //logic that is looking for cases where we didn't send one half buffer to the host before 868 | //the 2nd buffer ended because we only use each half buffer once. 869 | mask_xfer_err=false; 870 | //If requested samples are smaller than the buffer, reduce the size so that the 871 | //transfer completes sooner. 872 | //Also, mask the sending of aborts if the requested number of samples fit into RAM 873 | //Don't do this in continuous mode as the final size is unknown 874 | if(dev.cont==false){ 875 | if(buff_chunks>chunks_needed){ 876 | mask_xfer_err=true; 877 | buff_chunks=chunks_needed; 878 | //Dprintf("Reduce buf chunks to %d\n\r",buff_chunks); 879 | } 880 | } 881 | //Give dig and analog equal fractions 882 | //This is the size of each half buffer in bytes 883 | dev.d_size=(buff_chunks*chunk_size*d_nibbles)/(t_nibbles*2); 884 | dev.a_size=(buff_chunks*chunk_size*a_nibbles)/(t_nibbles*2); 885 | dev.samples_per_half=chunk_samples*buff_chunks/2; 886 | //Dprintf("Final sizes d %d a %d mask err %d samples per half %d\n\r" 887 | //,dev.d_size,dev.a_size,mask_xfer_err,dev.samples_per_half); 888 | 889 | //Clear any previous ADC over/underflow 890 | volatile uint32_t *adcfcs; 891 | adcfcs=(volatile uint32_t *)(ADC_BASE+0x8);//ADC FCS 892 | *adcfcs|=0xC00; 893 | 894 | 895 | //Ensure any previous dma is done 896 | //The cleanup loop also does this but it doesn't hurt to do it twice 897 | dma_channel_abort(admachan0); 898 | dma_channel_abort(admachan1); 899 | dma_channel_abort(pdmachan0); 900 | dma_channel_abort(pdmachan1); 901 | //Enable the initial chaing from the first half to 2nd, further chains are enabled based 902 | //on whether we can parse each half in time. 903 | channel_config_set_chain_to(&acfg0,admachan1); 904 | channel_config_set_chain_to(&pcfg0,pdmachan1); 905 | 906 | 907 | num_halves=0; 908 | dev.dbuf0_start=0; 909 | ccnt=0; 910 | dev.dbuf1_start=dev.d_size; 911 | dev.abuf0_start=dev.dbuf1_start+dev.d_size; 912 | dev.abuf1_start=dev.abuf0_start+dev.a_size; 913 | 914 | 915 | volatile uint32_t *adcdiv; 916 | adcdiv=(volatile uint32_t *)(ADC_BASE+0x10);//ADC DIV 917 | // Dprintf("adcdiv start %u\n\r",*adcdiv); 918 | // Dprintf("starting d_nps %u a_chan_cnt %u d_size %u a_size %u a_mask %X\n\r" 919 | // ,dev.d_nps,dev.a_chan_cnt,dev.d_size,dev.a_size,dev.a_mask); 920 | //Dprintf("start offsets d0 0x%X d1 0x%X a0 0x%X a1 0x%X samperhalf %u\n\r" 921 | // ,dev.dbuf0_start,dev.dbuf1_start,dev.abuf0_start,dev.abuf1_start,dev.samples_per_half); 922 | //Dprintf("starting data buf values 0x%X 0x%X\n\r",capture_buf[dev.dbuf0_start],capture_buf[dev.dbuf1_start]); 923 | uint32_t adcdivint=48000000ULL/(dev.sample_rate*dev.a_chan_cnt); 924 | if(dev.a_chan_cnt){ 925 | adc_run(false); 926 | // en, dreq_en,dreq_thresh,err_in_fifo,byte_shift to 8 bit 927 | adc_fifo_setup(false, true, 1, false, true); 928 | adc_fifo_drain(); 929 | //Dprintf("astart cnt %u div %f\n\r",dev.a_chan_cnt,(float)adcdivint); 930 | 931 | //This sdk function doesn't support support the fractional divisor 932 | // adc_set_clkdiv((float)(adcdivint-1)); 933 | //The ADC divisor has some not well documented limitations. 934 | //-A value of 0 actually creates a 500khz sample clock. 935 | //-Values below 96 don't work well (the SDK has comments about it 936 | //in the adc_set_clkdiv document) 937 | //It is also import to subtract one from the desired divisor 938 | //because the period of ADC clock is 1+INT+FRAC/256 939 | //For the case of a requested 500khz clock, we would normally write 940 | //a divisor of 95, but doesn't give the desired result, so we use 941 | //the 0 value instead. 942 | //Fractional divisors should generally be avoided because it creates 943 | //skew with digital samples. 944 | uint8_t adc_frac_int; 945 | adc_frac_int=(uint8_t)(((48000000ULL%dev.sample_rate)*256ULL)/dev.sample_rate); 946 | if(adcdivint<=96){ 947 | *adcdiv=0; 948 | }else{ 949 | *adcdiv=((adcdivint-1)<<8)|adc_frac_int; 950 | } 951 | //Dprintf("adcdiv %u frac %d\n\r",*adcdiv,adc_frac_int); 952 | 953 | //This is needed to clear the AINSEL so that when the round robin arbiter starts we start sampling on channel 0 954 | adc_select_input(0); 955 | adc_set_round_robin(dev.a_mask & 0x7); 956 | // en, dreq_en,dreq_thresh,err_in_fifo,byte_shift to 8 bit 957 | adc_fifo_setup(true, true, 1, false, true); 958 | 959 | 960 | //set chan0 to immediate trigger (but without adc_run it shouldn't start), chan1 is chained to it. 961 | // channel, config, write_addr,read_addr,transfer_count,trigger) 962 | dma_channel_configure(admachan0,&acfg0,&(capture_buf[dev.abuf0_start]),&adc_hw->fifo,dev.a_size,true); 963 | dma_channel_configure(admachan1,&acfg1,&(capture_buf[dev.abuf1_start]),&adc_hw->fifo,dev.a_size,false); 964 | adc_fifo_drain(); 965 | }//any analog enabled 966 | if(dev.d_mask){ 967 | //analyzer_init from pico-examples 968 | //Due to how PIO shifts in bits, if any digital channel within a group of 8 is set, 969 | //then all groups below it must also be set. We further restrict it in the tx_init function 970 | //by saying digital channel usage must be continous. 971 | /* pin count is restricted to 4,8,16 or 32, and pin count of 4 is only used 972 | Pin count is kept to a powers of 2 so that we always read a sample with a single byte/word/dword read 973 | for faster parsing. 974 | if analog is disabled and we are in D4 mode 975 | bits d_dma_bps d_tx_bps 976 | 0-4 0 1 No analog channels 977 | 0-4 1 1 1 or more analog channels 978 | 5-7 1 1 979 | 8 1 2 980 | 9-12 2 2 981 | 13-14 2 2 982 | 15-16 2 3 983 | 17-21 4 3 984 | */ 985 | dev.pin_count=0 ; 986 | if(dev.d_mask&0x0000000F) dev.pin_count+=4; 987 | if(dev.d_mask&0x000000F0) dev.pin_count+=4; 988 | if(dev.d_mask&0x0000FF00) dev.pin_count+=8; 989 | if(dev.d_mask&0x0FFF0000) dev.pin_count+=16; 990 | //If 4 or less channels are enabled but ADC is also enabled, set a minimum size of 1B of PIO storage 991 | if((dev.pin_count==4)&&(dev.a_chan_cnt)){dev.pin_count=8;} 992 | d_dma_bps=dev.pin_count>>3; 993 | //Dprintf("pin_count %d\n\r",dev.pin_count); 994 | uint16_t capture_prog_instr; 995 | capture_prog_instr = pio_encode_in(pio_pins, dev.pin_count); 996 | //Dprintf("capture_prog_instr 0x%X\n\r",capture_prog_instr); 997 | struct pio_program capture_prog = { 998 | .instructions = &capture_prog_instr, 999 | .length = 1, 1000 | .origin = -1 1001 | }; 1002 | uint offset = pio_add_program(pio, &capture_prog); 1003 | // Configure state machine to loop over this `in` instruction forever, 1004 | // with autopush enabled. 1005 | pio_sm_config c = pio_get_default_sm_config(); 1006 | //start at GPIO2 (keep 0 and 1 for uart) 1007 | sm_config_set_in_pins(&c, 2); 1008 | sm_config_set_wrap(&c, offset, offset); 1009 | 1010 | uint16_t div_int; 1011 | uint8_t frac_int; 1012 | div_int=frequency_count_khz(CLOCKS_FC0_SRC_VALUE_CLK_SYS)*1000/dev.sample_rate; 1013 | if(div_int<1) div_int=1; 1014 | frac_int=(uint8_t)(((frequency_count_khz(CLOCKS_FC0_SRC_VALUE_CLK_SYS)*1000%dev.sample_rate)*256ULL)/dev.sample_rate); 1015 | // Dprintf("PIO sample clk %u divint %d divfrac %d \n\r",dev.sample_rate,div_int,frac_int); 1016 | //Unlike the ADC, the PIO int divisor does not have to subtract 1. 1017 | //Frequency=sysclkfreq/(CLKDIV_INT+CLKDIV_FRAC/256) 1018 | sm_config_set_clkdiv_int_frac(&c,div_int,frac_int); 1019 | 1020 | //Since we enable digital channels in groups of 4, we always get 32 bit words 1021 | sm_config_set_in_shift(&c, true, true, 32); 1022 | sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_RX); 1023 | pio_sm_init(pio, piosm, offset, &c); 1024 | //Analyzer arm from pico examples 1025 | pio_sm_set_enabled(pio, piosm, false); //clear the enabled bit 1026 | //XOR the shiftctrl field with PIO_SM0_SHIFTCTRL_FJOIN_RX_BITS 1027 | //Do it twice to restore the value 1028 | pio_sm_clear_fifos(pio, piosm); 1029 | //write the restart bit of PIO_CTRL 1030 | pio_sm_restart(pio, piosm); 1031 | 1032 | #ifndef NODMA 1033 | channel_config_set_dreq(&pcfg0, pio_get_dreq(pio,piosm,false)); 1034 | channel_config_set_dreq(&pcfg1, pio_get_dreq(pio,piosm,false)); 1035 | 1036 | // number config buffer target piosm xfer size trigger 1037 | dma_channel_configure(pdmachan0,&pcfg0,&(capture_buf[dev.dbuf0_start]),&pio->rxf[piosm],dev.d_size>>2,true); 1038 | dma_channel_configure(pdmachan1,&pcfg1,&(capture_buf[dev.dbuf1_start]),&pio->rxf[piosm],dev.d_size>>2,false); 1039 | #endif 1040 | 1041 | //This is done later so that we start everything as close in time as possible 1042 | // pio_sm_set_enabled(pio, piosm, true); 1043 | } //dev.d_mask 1044 | //These must be at their initial value,(or zero for the 2ndhalf) otherwise it indicates they have started to countdown 1045 | //Dprintf("Tcount start d %u %u a %u %u\n\r",*tcountd0,*tcountd1,*tcounta0,*tcounta1); 1046 | //These must be the initial value for both 1047 | //Dprintf("Tcount dbg start d 0x%X 0x%X a 0x%X 0x%X\n\r",*tcountdbgd0,*tcountdbgd1,*tcountdbga0,*tcountdbga1); 1048 | //These catch cases in DMA coding where DMA engines have started too soon.. 1049 | 1050 | if((*tcountd0)!=(*tcountdbgd0)&&(dev.d_mask)){Dprintf("\n\r\n\rERROR: DMAD0 changing\n\r\n\r");} 1051 | if((*tcounta0)!=(*tcountdbga0)&&(dev.a_mask)){Dprintf("\n\r\n\rERROR: DMAA0 changing\n\r\n\r");} 1052 | if((*tcountd1)!=0){Dprintf("\n\r\n\rERROR: DMAD1 should start with 0 tcount\n\r\n\r");} 1053 | if((*tcounta1)!=0){Dprintf("\n\r\n\rERROR: DMAA1 should start with 0 tcount\n\r\n\r");} 1054 | 1055 | //Dprintf("LVL0mask 0x%X\n\r",dev.lvl0mask); 1056 | //Dprintf("LVL1mask 0x%X\n\r",dev.lvl1mask); 1057 | //Dprintf("risemask 0x%X\n\r",dev.risemask); 1058 | //Dprintf("fallmask 0x%X\n\r",dev.fallmask); 1059 | //Dprintf("edgemask 0x%X\n\r",dev.chgmask); 1060 | 1061 | // Dprintf("dma addr start d 0x%X 0x%X a 0x%X 0x%X\n\r",*taddrd0,*taddrd1,*taddra0,*taddra1); 1062 | //Dprintf("capture_buf base %p \n\r",capture_buf); 1063 | //Dprintf("capture_buf dig %p %p \n\r",&(capture_buf[dev.dbuf0_start]),&(capture_buf[dev.dbuf1_start])); 1064 | //Dprintf("capture_buf analog %p %p\n\r",&(capture_buf[dev.abuf0_start]),&(capture_buf[dev.abuf1_start])); 1065 | //Dprintf("PIOSMCLKDIV 0x%X\n\r",*pio0sm0clkdiv); 1066 | 1067 | //Dprintf("PIO ctrl 0x%X fstts 0x%X dbg 0x%X lvl 0x%X\n\r",*pioctrl,*piofstts,*piodbg,*pioflvl); 1068 | //Dprintf("DMA channel assignments a %d %d d %d %d\n\r",admachan0,admachan1,pdmachan0,pdmachan1); 1069 | //Dprintf("DMA ctr reg addrs a %p %p d %p %p\n\r",(void *) tstsa0,(void *)tstsa1,(void *)tstsd0,(void *)tstsd1); 1070 | //Dprintf("DMA ctrl reg a 0x%X 0x%X d 0x%X 0x%X\n\r",*tstsa0,*tstsa1,*tstsd0,*tstsd1); 1071 | //Enable logic and analog close together for best possible alignment 1072 | //warning - do not put printfs or similar things here... 1073 | tstart=time_us_32(); 1074 | adc_run(true); //enable free run sample mode 1075 | pio_sm_set_enabled(pio, piosm, true); 1076 | dev.started=true; 1077 | init_done=true; 1078 | 1079 | }//if dev.sending and not started 1080 | dma_check(&dev); 1081 | 1082 | 1083 | //In high verbosity modes the host can miss the "!" so send these until it sends a "+" 1084 | if(dev.aborted==true){ 1085 | Dprintf("sending abort !\n\r"); 1086 | my_stdio_usb_out_chars("!!!",3); 1087 | sleep_us(200000); 1088 | } 1089 | //if we abort or normally finish a run sending gets dropped 1090 | if((dev.sending==false)&&(init_done==true)){ 1091 | //Dprintf("Ending PIO ctrl 0x%X fstts 0x%X dbg 0x%X lvl 0x%X\n\r",*pioctrl,*piofstts,*piodbg,*pioflvl); 1092 | //The end of sequence byte_cnt uses a "$+" format. 1093 | //Send the byte_cnt to ensure no bytes were lost 1094 | if(dev.aborted==false){ 1095 | char brsp[16]; 1096 | //Give the host time to finish processing samples so that the bytecnt 1097 | //isn't dropped on the wire 1098 | sleep_us(100000); 1099 | Dprintf("Cleanup bytecnt %d\n\r",ccnt); 1100 | sprintf(brsp,"$%d%c",ccnt,'+'); 1101 | puts_raw(brsp); 1102 | } 1103 | 1104 | #ifdef NODMA 1105 | // if dma is disabled and sample sizes are small this can be used 1106 | // to pull the raw sample data from the pio fifos. 1107 | uint lvl; 1108 | lvl=pio_sm_get_rx_fifo_level(pio,piosm); 1109 | Dprintf("FIFOlvl 0x%X\n\r",lvl); 1110 | uint32_t fval; 1111 | for (int x=0;xtlval; 1183 | // uint32_t all_mask=d->lvl0mask | d->lvl1mask| d->risemask | d->fallmask | d->chgmask; 1184 | 1185 | 1186 | if(d->triggered==false) { 1187 | uint32_t matches=0; 1188 | matches|=(~cval & d->lvl0mask); 1189 | matches|=(cval & d->lvl1mask); 1190 | if(d->notfirst){ 1191 | matches|=(cval & ~tlval & d->risemask); 1192 | matches|=(~cval & tlval & d->fallmask); 1193 | matches|=(~cval & tlval & d->chgmask); 1194 | } 1195 | if(matches==all_mask){ 1196 | //Dprintf("Triggered c 0x%X l 0x%X \n\r",cval,tlval); 1197 | d->triggered=true; 1198 | //This sends the last val on a trigger because SW based trigger on the host needs to see its 1199 | //value so that rising/falling/edge triggeers will fire there too. 1200 | lbyte=0; 1201 | for(char b=0;b < d->d_tx_bps;b++){ 1202 | cbyte=tlval&0xFF; 1203 | txbuf[txbufidx]=(cbyte<>(7-b); 1205 | tlval>>=8; 1206 | txbufidx++; 1207 | } //for b 1208 | }//matches==all_mask 1209 | d->notfirst=true; 1210 | } 1211 | if(d->triggered){ 1212 | //Transmit samples if we have already triggered. 1213 | } 1214 | 1215 | //save trigger last value to support rising/falling/change values 1216 | // tlval=lval; 1217 | End of depracated trigger logic 1218 | */ 1219 | -------------------------------------------------------------------------------- /pico_sdk_sigrok/sr_device.c: -------------------------------------------------------------------------------- 1 | #include "sr_device.h" 2 | #include "hardware/uart.h" 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | int Dprintf(const char *fmt, ...) 10 | { 11 | va_list argptr; 12 | int len = 1; 13 | char _dstr[256]; 14 | 15 | memset(&_dstr, 0x00, sizeof(_dstr)); 16 | va_start(argptr, fmt); 17 | len = vsprintf(_dstr, fmt, argptr); 18 | va_end(argptr); 19 | 20 | if ((len > 0) && (len < 240)) 21 | { 22 | uart_puts(uart0, _dstr); 23 | uart_tx_wait_blocking(uart0); 24 | } 25 | else 26 | { 27 | uart_puts(uart0, "UART OVRFLW"); 28 | uart_tx_wait_blocking(uart0); 29 | } 30 | return len; 31 | } 32 | 33 | // reset as part of init, or on a completed send 34 | void reset(sr_device_t *d) 35 | { 36 | d->sending = 0; 37 | d->cont = 0; 38 | d->aborted = false; 39 | d->started = false; 40 | d->scnt = 0; 41 | // d->notfirst=false; 42 | // Set triggered by default so that we don't check for HW triggers 43 | // unless the driver sends a trigger command 44 | // d->triggered=true; 45 | // d->tlval=0; 46 | // d->lvl0mask=0; 47 | // d->lvl1mask=0; 48 | // d->risemask=0; 49 | // d->fallmask=0; 50 | // d->chgmask=0; 51 | }; 52 | // initial post reset state 53 | void init(sr_device_t *d) 54 | { 55 | reset(d); 56 | d->a_mask = 0; 57 | d->d_mask = 0; 58 | d->sample_rate = 5000; 59 | d->num_samples = 10; 60 | d->a_chan_cnt = 0; 61 | d->d_nps = 0; 62 | d->cmdstrptr = 0; 63 | } 64 | void tx_init(sr_device_t *d) 65 | { 66 | // A reset should have already been called to restart the device. 67 | // An additional one here would clear trigger and other state that had been updated 68 | // reset(d); 69 | d->a_chan_cnt = 0; 70 | for (int i = 0; i < NUM_A_CHAN; i++) 71 | { 72 | if (((d->a_mask) >> i) & 1) 73 | { 74 | d->a_chan_cnt++; 75 | } 76 | } 77 | // Nibbles per slice controls how PIO digital data is stored 78 | // Only support 0,1,2,4 or 8, which use 0,4,8,16 or 32 bits of PIO fifo data 79 | // per sample clock. 80 | d->d_nps = (d->d_mask & 0xF) ? 1 : 0; 81 | d->d_nps = (d->d_mask & 0xF0) ? (d->d_nps) + 1 : d->d_nps; 82 | d->d_nps = (d->d_mask & 0xFF00) ? (d->d_nps) + 2 : d->d_nps; 83 | d->d_nps = (d->d_mask & 0xFFFF0000) ? (d->d_nps) + 4 : d->d_nps; 84 | // Dealing with samples on a per nibble, rather than per byte basis in non D4 mode 85 | // creates a bunch of annoying special cases, so forcing non D4 mode to always store a minimum 86 | // of 8 bits. 87 | if ((d->d_nps == 1) && (d->a_chan_cnt > 0)) 88 | { 89 | d->d_nps = 2; 90 | } 91 | 92 | // Digital channels must enable from D0 and go up, but that is checked by the host 93 | d->d_chan_cnt = 0; 94 | for (int i = 0; i < NUM_D_CHAN; i++) 95 | { 96 | if (((d->d_mask) >> i) & 1) 97 | { 98 | // Dprintf("i %d inv %d mask %X\n\r",i,invld,d->d_mask); 99 | d->d_chan_cnt++; 100 | } 101 | } 102 | d->d_tx_bps = (d->d_chan_cnt + 6) / 7; 103 | d->sending = true; 104 | } 105 | // Process incoming character stream 106 | // Return 1 if the device rspstr has a response to send to host 107 | // Be sure that rspstr does not have \n or \r. 108 | int process_char(sr_device_t *d, char charin) 109 | { 110 | int tmpint, tmpint2, ret; 111 | // set default rspstr for all commands that have a dataless ack 112 | d->rspstr[0] = '*'; 113 | d->rspstr[1] = 0; 114 | // the reset character works by itself 115 | if (charin == '*') 116 | { 117 | reset(d); 118 | Dprintf("RST* %d\n\r", d->sending); 119 | return 0; 120 | } 121 | else if ((charin == '\r') || (charin == '\n')) 122 | { 123 | d->cmdstr[d->cmdstrptr] = 0; 124 | switch (d->cmdstr[0]) 125 | { 126 | case 'i': 127 | // SREGEN,AxxyDzz,00 - num analog, analog size, num digital,version 128 | sprintf(d->rspstr, "SRPICO,A%02d1D%02d,02", NUM_A_CHAN, NUM_D_CHAN); 129 | Dprintf("ID rsp %s\n\r", d->rspstr); 130 | ret = 1; 131 | break; 132 | case 'R': 133 | tmpint = atol(&(d->cmdstr[1])); 134 | if ((tmpint >= 5000) && (tmpint <= 120000016)) 135 | { // Add 16 to support cfg_bits 136 | d->sample_rate = tmpint; 137 | // Dprintf("SMPRATE= %u\n\r",d->sample_rate); 138 | ret = 1; 139 | } 140 | else 141 | { 142 | Dprintf("unsupported smp rate %s\n\r", d->cmdstr); 143 | ret = 0; 144 | } 145 | break; 146 | // sample limit 147 | case 'L': 148 | tmpint = atol(&(d->cmdstr[1])); 149 | if (tmpint > 0) 150 | { 151 | d->num_samples = tmpint; 152 | // Dprintf("NUMSMP=%u\n\r",d->num_samples); 153 | ret = 1; 154 | } 155 | else 156 | { 157 | Dprintf("bad num samples %s\n\r", d->cmdstr); 158 | ret = 0; 159 | } 160 | break; 161 | case 'a': 162 | tmpint = atoi(&(d->cmdstr[1])); // extract channel number 163 | if (tmpint >= 0) 164 | { 165 | // scale and offset are both in integer uVolts 166 | // separated by x 167 | sprintf(d->rspstr, "25700x0"); // 3.3/(2^7) and 0V offset 168 | // Dprintf("ASCL%d\n\r",tmpint); 169 | ret = 1; 170 | } 171 | else 172 | { 173 | Dprintf("bad ascale %s\n\r", d->cmdstr); 174 | ret = 1; // this will return a '*' causing the host to fail 175 | } 176 | break; 177 | case 'F': // fixed set of samples 178 | Dprintf("STRT_FIX\n\r"); 179 | tx_init(d); 180 | d->cont = 0; 181 | ret = 0; 182 | break; 183 | case 'C': // continous mode 184 | tx_init(d); 185 | d->cont = 1; 186 | Dprintf("STRT_CONT\n\r"); 187 | ret = 0; 188 | break; 189 | case 't': // trigger -format tvxx where v is value and xx is two digit channel 190 | /*HW trigger depracated 191 | tmpint=d->cmdstr[1]-'0'; 192 | tmpint2=atoi(&(d->cmdstr[2])); //extract channel number which starts at D2 193 | //Dprintf("Trigger input %d val %d\n\r",tmpint2,tmpint); 194 | if((tmpint2>=2)&&(tmpint>=0)&&(tmpint<=4)){ 195 | d->triggered=false; 196 | switch(tmpint){ 197 | case 0: d->lvl0mask|=1<<(tmpint2-2);break; 198 | case 1: d->lvl1mask|=1<<(tmpint2-2);break; 199 | case 2: d->risemask|=1<<(tmpint2-2);break; 200 | case 3: d->fallmask|=1<<(tmpint2-2);break; 201 | default: d->chgmask|=1<<(tmpint2-2);break; 202 | } 203 | //Dprintf("Trigger channel %d val %d 0x%X\n\r",tmpint2,tmpint,d->lvl0mask); 204 | //Dprintf("LVL0mask 0x%X\n\r",d->lvl0mask); 205 | //Dprintf("LVL1mask 0x%X\n\r",d->lvl1mask); 206 | //Dprintf("risemask 0x%X\n\r",d->risemask); 207 | //Dprintf("fallmask 0x%X\n\r",d->fallmask); 208 | //Dprintf("edgemask 0x%X\n\r",d->chgmask); 209 | }else{ 210 | Dprintf("bad trigger channel %d val %d\n\r",tmpint2,tmpint); 211 | d->triggered=true; 212 | } 213 | */ 214 | ret = 1; 215 | break; 216 | case 'p': // pretrigger count 217 | tmpint = atoi(&(d->cmdstr[1])); 218 | Dprintf("Pre-trigger samples %d cmd %s\n\r", tmpint, d->cmdstr); 219 | ret = 1; 220 | break; 221 | // format is Axyy where x is 0 for disabled, 1 for enabled and yy is channel # 222 | case 'A': /// enable analog channel always a set 223 | tmpint = d->cmdstr[1] - '0'; // extract enable value 224 | tmpint2 = atoi(&(d->cmdstr[2])); // extract channel number 225 | if ((tmpint >= 0) && (tmpint <= 1) && (tmpint2 >= 0) && (tmpint2 <= 31)) 226 | { 227 | d->a_mask = d->a_mask & ~(1 << tmpint2); 228 | d->a_mask = d->a_mask | (tmpint << tmpint2); 229 | // Dprintf("A%d EN %d Msk 0x%X\n\r",tmpint2,tmpint,d->a_mask); 230 | ret = 1; 231 | } 232 | else 233 | { 234 | ret = 0; 235 | } 236 | break; 237 | // format is Dxyy where x is 0 for disabled, 1 for enabled and yy is channel # 238 | case 'D': /// enable digital channel always a set 239 | tmpint = d->cmdstr[1] - '0'; // extract enable value 240 | tmpint2 = atoi(&(d->cmdstr[2])); // extract channel number 241 | if ((tmpint >= 0) && (tmpint <= 1) && (tmpint2 >= 0) && (tmpint2 <= 31)) 242 | { 243 | d->d_mask = d->d_mask & ~(1 << tmpint2); 244 | d->d_mask = d->d_mask | (tmpint << tmpint2); 245 | // Dprintf("D%d EN %d Msk 0x%X\n\r",tmpint2,tmpint,d->d_mask); 246 | ret = 1; 247 | } 248 | else 249 | { 250 | ret = 0; 251 | } 252 | break; 253 | default: 254 | Dprintf("bad command %s\n\r", d->cmdstr); 255 | ret = 0; 256 | } // case 257 | // Dprintf("CmdDone %s\n\r",d->cmdstr); 258 | d->cmdstrptr = 0; 259 | } 260 | else 261 | { // no CR/LF 262 | if (d->cmdstrptr >= 19) 263 | { 264 | d->cmdstr[18] = 0; 265 | Dprintf("Command overflow %s\n\r", d->cmdstr); 266 | d->cmdstrptr = 0; 267 | } 268 | d->cmdstr[d->cmdstrptr++] = charin; 269 | ret = 0; 270 | } // else 271 | // default return 0 means to not send any kind of response 272 | return ret; 273 | } // process_char 274 | -------------------------------------------------------------------------------- /pico_sdk_sigrok/sr_device.h: -------------------------------------------------------------------------------- 1 | #ifndef SR_DEVICE_H 2 | #define SR_DEVICE_H 3 | #include 4 | #include 5 | 6 | // Pin usage 7 | // GP0 and 1 are reserved for debug uart 8 | // GP2-GP22 are digital inputs 9 | // GP23 controls power supply modes and is not a board input 10 | // GP24-25 are not on the board and not used 11 | // GP26-28 are ADC. 12 | // number of analog channels 13 | #define NUM_A_CHAN 3 14 | // number of digital channels 15 | #define NUM_D_CHAN 21 16 | // Mask of bits 22:2 to use as inputs - 17 | #define GPIO_D_MASK 0x7FFFFC 18 | // Storage size of the DMA buffer. The buffer is split into two halves so that when the first 19 | // buffer fills we can send the trace data serially while the other buffer is DMA'dinto 20 | #define DMA_BUF_SIZE 220000 21 | // The size of the buffer sent to the CDC serial 22 | // The TUD CDC buffer is only 256B so it doesn't help to have more than this. 23 | #define TX_BUF_SIZE 260 24 | #define UART_BAUD 921600 25 | // This sets the point which we will send data from the txbuf to the usb cdc. 26 | // For the 5-21 channel RLE it must leave a spare ~83 entries to cover the case where 27 | // a new long steady input comes after deciding to not send a sample. 28 | //(Assuming 128KB samples per half, a max rle value of 1568 we can get 29 | // 256*1024/2/1568=83 max length rles on a steady input). 30 | // Other than that the value is not very specific because the usb tub code 31 | // implement a 256 entry fifo that queues things up and sends max length 64B transactions 32 | // 20 is arbitrarly picked to ensure that if we have even a little we send it so that 33 | // at least something goes across the link. 34 | #define TX_BUF_THRESH 20 35 | // Base value of sys_clk in khz. Must be <=125Mhz per RP2040 spec and a multiple of 24Mhz 36 | // to support integer divisors of the PIO clock and ADC clock 37 | #define SYS_CLK_BASE 120000 38 | // Boosted sys_clk in khz. Runs the part above its specifed frequency limit to support faster 39 | // processing of digital run length encoding which in some cases may allow for faster 40 | // streaming of digital only data. 41 | //**************************** 42 | // Use this at your own risk 43 | //*************************** 44 | // Frequency must be a 24Mhz multiple and less than 300Mhz to avoid known issues 45 | // The authors PICO failed at 288Mhz, but testing with 240Mhz seemed reliable 46 | // #define SYS_CLK_BOOST_EN 1 47 | // #define SYS_CLK_BOOST_FREQ 240000 48 | 49 | typedef struct 50 | { 51 | uint32_t sample_rate; 52 | uint32_t num_samples; 53 | uint32_t a_mask, d_mask; 54 | uint32_t samples_per_half; // number of samples for one of the 4 dma target arrays 55 | uint8_t a_chan_cnt; // count of enabled analog channels 56 | uint8_t d_chan_cnt; // count of enabled digital channels 57 | uint8_t d_tx_bps; // Digital Transmit bytes per slice 58 | // Pins sampled by the PIO - 4,8,16 or 32 59 | uint8_t pin_count; 60 | uint8_t d_nps; // digital nibbles per slice from a PIO/DMA perspective. 61 | uint32_t scnt; // number of samples sent 62 | char cmdstrptr; 63 | char cmdstr[20]; // used for parsing input 64 | uint32_t d_size, a_size; // size of each of the two data buffers for each of a& d 65 | uint32_t dbuf0_start, dbuf1_start, abuf0_start, abuf1_start; // starting memory pointers of adc buffers 66 | char rspstr[20]; 67 | // mark key control variables voltatile since multiple cores might access them 68 | volatile bool started; 69 | volatile bool sending; 70 | volatile bool cont; 71 | volatile bool aborted; 72 | /*Depracated trigger logic 73 | //If HW trigger enabled, uncomment all usages 74 | //volatile bool notfirst; //Have we processed at least a first sample (so that lval is correct 75 | // volatile bool triggered; 76 | // uint32_t tlval; //last digital sample value - must keep it across multiple calls to send_slices for trigger 77 | // uint32_t lvl0mask,lvl1mask,risemask,fallmask,chgmask; 78 | End depracated trigger logic*/ 79 | } sr_device_t; 80 | 81 | // initialize debug uart 82 | int Dprintf(const char *fmt, ...); 83 | 84 | // Process incoming character stream 85 | int process_char(sr_device_t *d, char charin); 86 | 87 | // reset as part of init, or on a completed send 88 | void reset(sr_device_t *d); 89 | 90 | // initial post reset state 91 | void init(sr_device_t *d); 92 | 93 | // Initialize the tx buffer 94 | void tx_init(sr_device_t *d); 95 | 96 | // Process incoming character stream 97 | // Return 1 if the device rspstr has a response to send to host 98 | // Be sure that rspstr does not have \n or \r. 99 | int process_char(sr_device_t *d, char charin); 100 | 101 | #endif /* SR_DEVICE_H */ 102 | -------------------------------------------------------------------------------- /pulseview/Readme.md: -------------------------------------------------------------------------------- 1 | This is an unofficial Pulseview windows installer to use the raspberry pi pico on windows. 2 | 3 | Github limits filesizes to 25MB but it is 40MB. You should be able to download this without creating a drobox account. 4 | 5 | Revision 2 is now released, and available here. Since this is a major release, the PICO will need a new UF2 file to match. 6 | 7 | https://www.dropbox.com/s/i1guje5kg89yi7a/pulseview-0.5.0-git-7e5c839-installer_rev2.exe?dl=0 8 | 9 | 10 | It is recommended that you uninstall previous versions first. 11 | 12 | You may need to install this to get msvcr100.dll 13 | https://www.microsoft.com/en-us/download/details.aspx?id=26999![image](https://user-images.githubusercontent.com/99157244/158026832-9f6b139b-6ea1-4aa0-80c2-4fb8def398fa.png) 14 | 15 | Other windows related information is here (but note the links to install mscvr100.dll are out of date). 16 | https://sigrok.org/wiki/Windows 17 | 18 | Old rev1 is here, but the old UF2 is no longer available (unless you use git pulls to get an older version). 19 | 20 | https://www.dropbox.com/s/rnktz830phgl1ag/pulseview-0.5.0-git-7e5c839-installer_rev1.exe?dl=0 21 | --------------------------------------------------------------------------------